March 2011

Hi,
WPF provides two main ways for implementing data validation: ValidationRule and IDataErrorInfo. In this post is focused on IDataErrorInfo.

The demo project is available hereand the below images displays the result from an UI point of view:

Using ValidationRule you are able to validate user inputs directly into UI (View). This way consists in implementing a class that extends .Net ValidationRule and using your class into Binding. You can check an example here.

Using IDataErrorInfo you are able to validate user inputs in both UI and Business Logic too (ViewModel). This way is more MVVM oriented and allow performing validation in different layers (View and ViewModel) sharing a common validation code.

The first step consists into implementing IDataErrorInfo interface into the class that contains a Property that will be involved in UI binding. IDataErrorInfo consists into two properties: the Error property that tells what is wrong with this object, and the Item property that gets the error message of the specified property. Regardless of your object you can implement IDataErrorInfo interface in the following way:

You might ask “why”? The answer is easier you can imagine: the GetValidationError method we are going to implement will be also used by IsValid property into other layers (typically ViewModel).
In other words the IDataErrorInfo is used by .Net into binding expressions, while IsValid property can be used into code behind layers.