Enabling Validation in Silverlight 4 with IDataErrorInfo

18 November 2009

One of the new features of Silverlight 4 Beta is the addition of the IDataErrorInfo interface. In Silverlight 3 we throw exceptions when a property value is invalid. The IDataErrorInfo interface has been around in .NET but is new to Silverlight 4 beta. It allows you to invalidate property values without throwing exceptions.

Implementing this interface is pretty straightforward, though there are several ways to do it. To help you get jumpstarted with this new feature, I included some sample code I wrote that you can use to implement the IDataErrorInfo interface to perform data validation. The controls in Silverlight 4 beta, such as the DataForm, observe the IDataErrorInfo interface so they know how to handle the validation issues. This means that when a validation rule is violated in the IDataErrorInfo implementation for an entity, the controls will display the appropriate invalid state to the user.

The sample code below uses a ValidationHandler class I created which deals with the IDataErrorInfo details. I created this class to help consolidate this logic which will be used in several entities in a project. You can call the ValidateRule method and pass to it the property name, the error message, and a delegate for the rule to check. This can easily be extended to create a canned set of rules.

Here is the class sample showing an entity with some properties and rules. The sample also shows the ValidationHandler utility class. Enjoy!