Sunday, September 18, 2011

IDataErrorInfo and SpecExpress

We recently received a post from Karl:

I didn't see an example or documentation for using SpecExpress along with IDataErrorInfo.  Is it possible?
Thank you, SpecExpress looks great,

Well Thanks Karl!  We think SpecExpress looks great to!  Using IDataErrorInfo with SpecExpress is VERY possible.  A matter of fact it makes implementing IDataErrorInfo in your model classes extremely simple.

For those that are unfamiliar with IDataErrorInfo, IDataErrorInfo is an interface that a UI framework such as WPF, Silverlight, and MVC can bind to when data validation errors occur.  The interface exposes two member properties:

  • Error – gets an error message indicating what is wrong with the object
  • Item – an index based property that gets an error message for a given property given the property name provided as the index

Implementing these two interfaces is as simple as this:

using System.ComponentModel;
using SpecExpress;

namespace MvcApplication5.Models
public class Contact : IDataErrorInfo
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }

#region IDataErrorInfo
public string this[string columnName]
return ValidationCatalog.ValidateProperty(this, columnName).ToString();

public string Error
get { return ValidationCatalog.Validate(this).ToString(); }


You may even want to consider implementing the interface in an abstract base class that all your model classes inherit from!  The beauty of this code is the simplification you get in defining the model class.  The aspect of business rules delegated to SpecExpress’ ValidationCatalog through a single line of code for each property!

Of course, using MVC, the IDataErrorInfo interface is called on the server side each time the data is posted to the controller through a post back.  Sometimes, especially for lengthy forms, this may not be the optimum user experience.  With SpecExpress, we have written an MVC Integration library that leverages the JQuery Validation library for client side validation.  Through the MVC Integration, the appropriate client side validation is automatically called based upon the validation rules expressed and registered in the ValidationCatalog.  See the documentation and sample code in the source code for more specifics on this integration.

No comments:

Post a Comment