Any mobile app that accepts user input should ensure that the input is valid. This could involve, for example, checking that input contains only characters in a particular range, or is of a certain length. Without validation, a user can supply data that can cause the app to fail.
In the context of MVVM, user input can be synchronously validated client-side in view model objects or in model objects. However, validating data in view models often means duplicating model properties. Instead, view models can delegate validation to the model objects they contain, with validation then being performed on the model objects. Validation rules can be specified on the model properties by using data annotations that derive from the ValidationAttribute class.
I’ve created a validation sample implements validation using this approach, which can be found on GitHub. The following diagram shows a high-level overview of the classes involved in validation:
To participate in validation, model classes must derive from the ValidatableBase class, which provides an error container whose contents are updated whenever a model class property value changes. The Validator and ValidatableBase classes both implement INotifyPropertyChanged in order to provide property change notification.
The SetProperty method in the ValidatableBase class performs validation when a model property is set to a new value. The validation rules come from data annotation attributes that derive from the ValidationAttribute class. The attributes are taken from the declaration of the model property being validated.
Users are notified of validation errors by highlighting the controls that contain the invalid data with red borders, and by displaying error messages that inform the user why the data is invalid, as shown in the following screenshot:
Over the coming weeks I’m going to explore this validation approach in a series of blog posts:
- Specifying validation rules.
- Triggering validation.
- Displaying validation errors.
In the meantime, the code can be downloaded from GitHub.