Main Content

Validate Property Values

Property Validation in Class Definitions

MATLAB®property validation enables you to place specific restrictions on property values. You can use validation to constrain the class and size of property values. Also, you can use functions to establish criteria that the property value must conform to. MATLAB defines a set of validation functions and you can write your own validation functions.

The use of property validation is optional in class definitions.

Additional Information on Property Validation

For more information on property validation, seeProperty Class and Size Validation,Property Validation Functions, andMetadata Interface to Property Validation.

Validation Syntax

The highlighted area in the following code shows the syntax for property validation.

Property validation includes any of the following:

  • Size — The length of each dimension, specified as a positive integer or a colon. A colon indicates that any length is allowed in that dimension. The value assigned to the property must conform to the specified size or be compatible with the specified size. For more information, seeProperty Size Validation.

  • 一个MATLAB类的类的名称。在瓦尔ue assigned to the property must be of the specified class or convertible to the specified class. Use any MATLAB class or externally defined class that is supported by MATLAB, except for Java®and COM classes. For more information, seeProperty Class Validation.

  • Functions — A comma-separated list of validation function names. MATLAB passes the value assigned to the property to each the validation functions after applying any possible class and size conversions. Validator functions throw errors if the validation fails, but do not return values. For more information, seeProperty Validation Functions.

    For a list of MATLAB validation functions, seeProperty Validation Functions.

Using Property Validation

Use property validation for public properties to control the values user code assigns to the properties.

如果你想限制对固定的属性值set of identifiers, create an enumeration class for these identifiers and constrain the property to this class. For information on enumeration classes, seeDefine Enumeration Classes.

MATLAB type conversion rules apply to property validation. For example, MATLAB can coerce from one to another numeric type. Therefore, restricting a property value to a specific numeric type, such as double does not prevent the assignment of other numeric types to the property.

To ensure that a property can be assigned only a specific type of value, restrict the property to a type that supports only the desired type conversions or use a validation function to specify the exact class allowed for the property instead of specifying the property type. MATLAB evaluates the type specification before executing any validation functions. For more information, seeOrder of Validation.

Specify Valid Default

Ensure that any default value assigned to the property meets the restrictions imposed by the specified validation. If you do not specify a default value, MATLAB creates a default value by assigning an empty object of the specified class or by calling the default constructor if size restriction does not allow the use of an empty default value. The default constructor must return an object of the correct size.

Sample Class Using Property Validation

TheValidateProps类定义了三个属性与验证。

classdefValidatePropspropertiesLocation(1,3) double {mustBeReal, mustBeFinite}Label(1,:) char {mustBeMember(Label,{'High','Medium','Low'})}='Low'State(1,1) matlab.lang.OnOffSwitchStateendend
  • Locationmust be a 1-by-3 array of classdoublewhose values are real, finite numbers.

  • Labelmust be acharvector that is either'High','Medium', or'Low'.

  • Statemust be an enumeration member of thematlab.lang.OnOffSwitchStateclass (offoron).

Validation at Instantiation

Creating an object of theValidatePropsclass performs the validation on implicit and explicit default values:

a = ValidateProps
a = ValidateProps with properties: Location: [0 0 0] Label: 'Low' State: off

When creating the object, MATLAB:

  • Initializes theLocationproperty value to[0 0 0]to satisfy the size and class requirements.

  • Sets theLabelproperty to its default value,'Low'. The default value must be a member of the allowed set of values. The emptycharimplicit default value would cause an error.

  • Sets theStateproperty to theoffenumeration member defined by thematlab.lang.OnOffSwitchStateclass.

For information on how MATLAB selects default values, seeDefault Values Per Size and Class.

Order of Validation

When a value is assigned to the property, including default values that are specified in the class definition, MATLAB performs validation in this order:

  • Class validation — This validation can cause conversion to a different class, such as conversion of achartostring. Assignment to properties follows MATLAB conversion rules for arrays.

  • Size validation — This validation can cause size conversion, such as scalar expansion or conversion of a column vector to a row vector. Assignment to a property that specifies a size validation behaves the same as assignment to any MATLAB array. For information on indexed assignment, seeArray Indexing.

  • Validator functions — MATLAB passes the result of the class and size validation to each validation function, in left to right order. An error can occur before all validation functions have been called, which ends the validation process.

  • Set method — MATLAB performs property validation before calling a property set method, if one is defined for that property. Assignment to the property within a property set or get method does not apply the validation again. Often, you can replace property set methods using property validation.

Property Validation Errors

TheValuePropclass uses size, class, and function validation to ensure that an assignment to theValueproperty is a double scalar that is not negative.

classdefValueProppropertiesValue(1,1) double {mustBeNonnegative}= 0endend

This statement attempts to assign a cell array to the property. This assignment violates the class validation.

a.Value = {10,20};
Error setting property 'Value' of class 'ValueProp': Invalid data type. Value must be double or be convertible to double.

This statement attempts to assign a 1-by-2 double array to the property. This assignment violates the size validation.

a.Value = [10 20];
Error setting property 'Value' of class 'ValueProp': Size of value must be scalar.

This statement attempts to assign a scalar double to the property. This assignment fails the function validation, which requires a nonnegative number.

a.Value = -10;
Error setting property 'Value' of class 'ValueProp': Value must be nonnegative.

在瓦尔idation process ends with the first error encountered.

Abstract Property Validation

You can define property validation for abstract properties. The validation applies to all subclasses that implement the property. However, subclasses cannot use any validation on their implementation of the property. When inheriting validation for a property from multiple classes, only a single Abstract property in one superclass can define the validation. None of the superclasses can define the property as nonAbstract.

Objects Not Updated When Changing Validation

If you change the property validation while objects of the class exist, MATLAB does not attempt to apply the new validation to existing property values. However, MATLAB does apply the new validation when you make assignments to the properties of existing objects.

Validation During Load Operation

When saving an object to aMATfile, MATLAB saves all nondefault property values with the object. When loading the object, MATLAB restores these property values in the newly created object.

If a class definition changes the property validation such that the loaded property value is no longer valid, MATLAB substitutes the currently defined default value for that property. However, theloadfunction suppresses the validation errors that occur before assigning the default value from the current class definition. Therefore, validation errors are silently ignored during load operations.

To illustrate this behavior, this example creates, saves, and loads an object of theMonthTempclass. This class restricts theAveTempproperty to a cell array.

classdefMonthTemppropertiesAveTempcellendend

Create aMonthTempobject and assign a value to theAveTempproperty.

a = MonthTemp; a.AveTemp = {'May',70};

Save the object usingsave.

saveTemperatureFilea

Edit the property definition to change the validation class for theAveTempproperty from cell array tocontainers.Map.

classdefMonthTemppropertiesAveTempcontainers.Mapendend

Load the saved object with the new class definition on the MATLAB path. MATLAB cannot assign the saved value to theAveTempproperty because the cell array,{'May',70}, is not compatible with the current requirement that the property value be acontainers.Mapobject. MATLAB cannot convert a cell array to acontainers.Map.

To address the incompatibility, MATLAB sets theAveTempproperty of the loaded object to the current default value, which is an emptycontainers.Mapobject.

loadTemperatureFileaa.AveTemp ans = Mapwithproperties:Count: 0 KeyType: char ValueType: any

The loaded object has a different value assigned to theAveTempproperty because the saved value is now invalid. However, the load process suppresses the validation error.

To prevent loss of data when changing class definitions and reloading objects, implement aloadobjmethod or class converter method that enables the saved values to satisfy the current property validation.

For more information on saving and loading objects, seeSave and Load Process for Objects.

Related Topics