Validations in WPF Using ValidationRule

WPF provides a very simple way for Data Validation. As most of the times we have to take input form user so there is a need of validation logic to ensure that the entered data is valid. A very simple way is to apply or associate Validation Rules with Binding.

WPF has a ValidationRule Class. It is a build-in class which provides a way to create custom rule for the validity of user input.

When we use Binding Model in WPF, we can associate ValidationRules with the binding object.




The binding engine checks each ValidationRule associated with the binding object everytime the control gets an input value from the user. The ValidationRule object checks the value of property whether it is valid or not. We have 2 types of ValidationRule objects in WPF :
1. ExceptionValidationRule
2. DataErrorValidationRule

ExceptionValidationRule

It checks for the exceptions that are raised during the updation of the source property. Example we have a property age that accepts integer value and it is binded to UI control ageTextbox. If in age Textbox user enters a value that cannot be converted to integer, an exception is thrown.
Alternative : In Binding set ValidatesOnExceptions property equal to True.

DataErrorValidationRule

It checks for the errors that are raised by the binding object(which implements IDataErrorInfo Interface)
Alternative : In Binding set ValidatesOnDataErrors property equal to True.

Side Note :
You can create your own custom validation rules by making a subclass of ValidationRule Class and by implementing its Validate() Method

This article is still in updation process.. Sorry for Inconvenience.. ComeBack soon for full understanding!!!