Validating User Input in Xamarin.Forms II
Previously I introduced a high-level overview of an approach to validating user input in Xamarin.Forms. This approach involves specifying validation rules on model objects, invoking validation when a model property values changes, and then displaying any error messages. In this blog post I’m going to explore how to specify validation rules on model objects.
Specifying Validation Rules
Validation rules are specified by adding data annotation attributes, that derive from the ValidationAttribute class, to properties in model classes that require validation.
The following code example shows the User class, where the properties are decorated with validation attributes:
The Required attribute specifies that a validation failure occurs if the field is null, contains an empty string, or contains only white-space characters. The RegularExpression attribute specifies that a property must match the regular expression given by the NAMESREGEXPATTERN constant. This regular expression allows user input to consist of all unicode name characters as well as spaces and hyphens, as long as the spaces and hyphens don’t occur in sequences and are not leading or trailing characters. The StringLength attribute specifies the minimum and maximum length of characters that are allowed. Each attribute also sets an ErrorMessage property, which stores the error message to be displayed if validation fails.
It’s worth browsing the DataAnnotations namespace in order to discover all the different validation attributes. As well as the general attributes mentioned above, it contains specific attributes capable of validating email addresses, credit card numbers, and phone numbers. In addition, it also provides a CustomValidation attribute, which specifies an application-provided method to be invoked to validate the property whenever a value is assigned to it.
To participate in validation a model class must derive from the ValidatableBase class, so that model property values will be validated when they change. In my next blog post I’ll explore this topic further. In the meantime, the code can be downloaded from GitHub.