Using DataAnnotation Attributes
Validating Input Through Data Annotations
With the WPF framework you can take advantage of the System.ComponentModel.DataAnnotations assembly. The following code snippet demonstrates how to use data annotation attributes to validate a property value. It is even better when you use RIA services, since this code will be automatically added for you by the RIA Service's code generator.
Example 1: Creating DataAnnotationAttributesValidationViewModel class
In order to use DataAnnotations you should add a reference to the System.ComponentModel.DataAnnotations assembly.
Note that you have to invoke the Validator.ValidateProperty method before setting a new value in the property setter.
Now we need to define several RadMaskedInput controls in XAML for displaying the sample data:
Example 2: Defining several RadMaskedInput controls
Note that you have set AllowInvalidValues to True. This ensures that the Setter of the properties will be fired even if the DataAnnotaion Validation does not succeed.
And finally we need to set the DataContext accordingly:
Example 3: Setting the DataContext to the view model
Below you can see how the MaskedInputs are being validated:
Regular Expressions
The MaskedInput suite of controls allow validation through Regular Expressions. In order to implement regex validation you will need a view model implementing the INotifyPropertyChanged interface. For the purpose of this tutorial we will define a ViewModel that contains Email and WebAddress properties. For each property we will apply a regular expression to validate the user's input in the MaskedInput control that will display the property accordingly.
First, we need a view model:
Example 4: Creating MaskedInputViewModel class
Note that you have to invoke the Validator.ValidateProperty method before setting a new value in the property setter.
In the above MaskedInputViewModel implementation it is important to note the regular expressions that validate the Email and WebAddress properties, as well as the custom ErrorMessage that is defined for each property. In order to apply such attributes that specify validation rules, you need to add a reference to the System.ComponentModel.DataAnnotations namespace.
Then you can define the RadMaskedInput controls that will display the Email and WebAddress business properties:
Example 5: Defining RadMaskedInput controls in XAML
Note that you have set AllowInvalidValues to True. This ensures that the Setter of the properties will be fired even if the DataAnnotaion Validation does not succeed.
And finally you need to set the MaskedInputViewModel as DataContext of the MaskedTextInput controls: