Property Validation Functions

Validate Property Using Functions

Use property validation functions in class definitions to impose specific restrictions on property values. A validation function accepts a potential property value as an argument and issues an error if the value does not meet the specific requirement imposed by the function.

During the validation process, MATLAB® passes the value to each validation function listed in the class definition. MATLAB calls each function from left to right and throws the first error encountered. The value passed to the validation functions is the result of any conversion applied by the class and size specifications. For more information on class and size validation, see Property Class and Size Validation.

For a list of MATLAB validation functions, see MATLAB Validation Functions

Validation Function Syntax

Specify validation functions as a comma-separated list of function names or function calls with arguments, enclosed in braces.

classdef MyClass
   properties
      Prop {fcn1,fcn2,...} = defaultValue
   end
end

MATLAB passes the potential property value to the validation function implicitly. However, if the validation function requires input arguments in addition to the potential property value, then you must include both the property and the additional arguments. Additional arguments must be literal values and cannot reference variables. Literal values are nonsymbolic representations, such as numbers and text.

For example, consider the function mustBeGreaterThan. It requires a limiting value as an input parameter. This validation function requires that a property value must be greater than this limiting value.

Pass the property as the first argument. Use the property name, but do not enclose the name in quotation marks. This property definition restricts Prop to values greater than 10.

properties
   Prop {mustBeGreaterThan(Prop,10)}
end

Using Validation Functions

The following class specifies validation functions for each property.

  • Data must be numeric and finite.

  • Interp must be one of the three options listed. Specify a default value for this property to satisfy this requirement.

classdef ValidatorFunction
   properties
      Data {mustBeNumeric, mustBeFinite}
      Interp {mustBeMember(Interp,{'linear','cubic','spline'})} = 'linear'
   end
end

Creating a default object of the class shows the initial values.

a = ValidatorFunction
a = 

  ValidatorFunction with properties:

      Data: []
    Interp: 'linear'

Assigning values to properties calls the validation functions.

a.Data = 'cubic'
Error setting property 'Data' of class 'ValidatorFunction':
Value must be numeric.

Because the Data property validation does not include a numeric class, there is no conversion of the char vector to a numeric value. If you change the validation of the Data property to specify the class as double, MATLAB converts the char vector to a double array.

properties
   Data double {mustBeNumeric, mustBeFinite}
end

The assignment to the char vector does not produce an error because MATLAB converts the char vector to class double.

a.Data = 'cubic'
a = 

  ValidatorFunction with properties:

      Data: [99 117 98 105 99]
    Interp: 'linear'

Assignment to the Interp property requires an exact match.

a = ValidatorFunction;
a.Interp = 'cu'
Error setting property 'Interp' of class 'ValidatorFunction':
Value must be a member of this set
    linear
    cubic
    spline

Using an enumeration class provides inexact matching and case insensitivity.

Enumeration Class for Inexact Matching

Property validation using an enumeration class provides these advantages:

  • Inexact, case-insensitive matching for unambiguous char vectors or string scalars

  • Conversion of inexact matches to correct values

For example, suppose that you define the InterpMethod enumeration class for the Interp property validation.

classdef InterpMethod
   enumeration
      linear
      cubic
      spline
   end
end

Change the Interp property validation to use the InterpMethod class.

classdef ValidatorFunction
   properties
      Data {mustBeNumeric, mustBeFinite}
      Interp InterpMethod
   end
end

Assign a value matching the first few letters of 'cubic'.

a = ValidatorFunction;
a.Interp = 'cu'
a = 

  ValidatorFunction with properties:

      Data: []
    Interp: cubic

MATLAB Validation Functions

MATLAB defines functions for use in property validation. These functions support common use patterns for validation and provide descriptive error messages. This table lists the MATLAB validation functions, their meanings, and the MATLAB functions used by the validation functions.

Name

Meaning

Functions Called on Inputs

mustBePositive(value)

value > 0

gt, isreal, isnumeric, islogical

mustBeNonpositive(value)

value <= 0

ge, isreal, isnumeric, islogical

mustBeFinite(value)

value has no NaN and no Inf elements.

isfinite

mustBeNonNan(value)

value has no NaN elements.

isnan

mustBeNonnegative(value)

value >= 0

ge, isreal, isnumeric, islogical

mustBeNegative(value)

value < 0

lt, isreal, isnumeric, islogical

mustBeNonzero(value)

value ~= 0

eq, isnumeric, islogical

mustBeGreaterThan(value,c)

value > c

gt, isscalar, isreal, isnumeric, islogical

mustBeLessThan(value,c)

value < c

lt, isreal, isnumeric, islogical

mustBeGreaterThanOrEqual(value,c)

value >= c

ge, isreal, isnumeric, islogical

mustBeLessThanOrEqual(value,c)

value <= c

le, isreal, isnumeric, islogical

mustBeNonempty(value)

value is not empty.

isempty

mustBeNonsparse(value)

value has no sparse elements.

issparse

mustBeNumeric(value)

value is numeric.

isnumeric

mustBeNumericOrLogical(value)

value is numeric or logical.

isnumeric, islogical

mustBeReal(value)

value has no imaginary part.

isreal

mustBeInteger(value)

value == floor(value)

isreal, isfinite, floor, isnumeric, islogical

mustBeMember(value,S)

value is an exact match for a member of S.

ismember

Define Validation Functions

Validator functions are ordinary MATLAB functions that are designed for the specific purpose of validating property values. Functions used as property validators:

  • Accept the potential property value as an input argument

  • Do not return values

  • Throw errors if the validation fails

Creating your own validation function is useful when you want to provide specific validation that is not available using the MATLAB validation functions. You can create local functions within the class file or place the function on the MATLAB path to be available for use in any class.

For example, the ImData class uses a local function to define a validator that restricts the Data property to a specific range of numeric values.

classdef ImData
   properties
      Data {mustBeNumeric, mustBeInRange(Data,[0,255])} = 0
   end
end
function mustBeInRange(a,b)
   if any(a(:) < b(1)) || any(a(:) > b(2))
      error(['Value assigned to Data property is not in range ',...
         num2str(b(1)),'...',num2str(b(2))])
   end
end

When you create an instance of the ImData class, MATLAB validates that the default value is numeric, in the range 0...255, and not empty.

a = ImData
a = 

  ImData with properties:

    Data: 0

Property assignment invokes the validators in left-to-right order. Assigning a char vector to the Data property causes an error thrown by mustBeNumeric.

a.Data = 'red'
Error setting property 'Data' of class 'ImData':
Value must be numeric.

Assigning a numeric value that is out of range causes an error thrown by mustBeInRange.

a.Data = -1
Error setting property 'Data' of class 'ImData':
Value assigned to Data property is not in range 0...255

Add Support for Validation Functions

Support MATLAB validation functions for objects of your class by implementing the dependent functions as methods of your class. To determine which methods to implement for each function, see the validation function reference pages listed in this table MATLAB Validation Functions.

For example, suppose that you want your class to support the mustBeGreaterThan validation function. Overload these MATLAB functions as methods in your class:

  • isreal — Always return logical true because mustBeGreaterThan does not support complex numbers.

  • gt — The second object in the comparison must be scalar, as required by mustBeGreaterThan.

The SupportmBGT class implements support for mustBeGreaterThan.

classdef SupportmBGT
   properties
      Prop(1,1) double {mustBeReal}
   end
   methods
      function obj = SupportmBGT(data)
         if nargin > 0
            obj.Prop = data;
         end
      end
      function tf = isreal(obj)
         tf = true;
      end
      function tf = gt(obj1, obj2)
         tf = [obj1(:).Prop] > obj2.Prop;
      end
   end
end

Use mustBeGreaterThan with objects of this class:

a = SupportmBGT(10);
b = SupportmBGT(12);
mustBeGreaterThan(a,b)
Error using mustBeGreaterThan (line 19)
Value must be greater than the comparison value.

Related Topics