Implementing Responsive Data Validation

Data validation goes hand in hand with data input forms and is essential for promoting clean, usable data. While the UI controls in WPF can automatically corroborate the fact that values entered match the type of their data bound properties, they cannot validate the correctness of the data entered.

For example, a TextBox control that is data bound to an integer may highlight an error if a user entered a non-numeric value, but it wouldn't validate the fact that the number entered had the correct number of digits, or that the first four digits were appropriate for the type of credit card specified.

In order to validate these types of data correctness when using MVVM, we'll need to implement one of the .NET validation interfaces. In this chapter, we'll examine in detail the available interfaces, looking at a number of implementations and explore the other validation-related features that WPF provides us with. Let's start by looking at the validation system.

In WPF, the validation system very much revolves around the static Validation class. This class has several Attached Properties, methods, and an Attached Event that support data validation. Each binding instance has a ValidationRules collection that can contain ValidationRule elements.

WPF provides three built-in rules:

Each time an attempt is made to update a data source property, the binding engine first clears the Validation.Errors collection and then checks the binding's ValidationRules collection to see whether it contains any ValidationRule elements. If it does, it calls each rule's Validate method in turn until they all pass, or one returns an error.

When a data bound value fails the condition in the Validation method of a ValidationRule element, the binding engine adds a new ValidationError object to the Validation.Errors collection of the data binding target control.

This, in turn, will set the Validation.HasError Attached Property of the element to true and, if the NotifyOnValidationError property of the binding is set to true, the binding engine will also raise the Validation.Error Attached Event on the data binding target.