Monday, November 14, 2011

Custom Validation using ASP.NET4 IValidateableObject

Let's pick up the Template class of my previous blog for this demo and implement duplicate Template Name check validation.
The class design of the Template class is as follows:


using System.ComponentModel;
using System.ComponentModel.DataAnnotations;

public partial class Template : IValidatableObject
{
public Template()
{
}

public int TemplateId { get; set; }
public string Name { get; set; }
public byte Active { get; set; }
public System.DateTime Effective { get; set; }
public Nullable Expiring { get; set; }
public string Description { get; set; }
public string Notes { get; set; }
public int ChangedBy { get; set; }
public System.DateTime ChangedAt { get; set; }

public IEnumerable Validate(ValidationContext validationContext)
{
if (this.State == System.Data.EntityState.Added)
{
using (SampleDBEntities db = new SampleDBEntities())
{
if (db.Templates.ToList().Exists(m => m.Name.ToUpper() == this.Name.ToUpper()))
{
yield return new ValidationResult("Duplicate template name", new List { "Name" });
}
}
}
}

}


In the code above, we have implemented the Validate() method of IValidatableObject to check if there is any Template with the same name. The "yield" construct is used to append this validation to other server side validations applied to the Template model class.

No comments:

Post a Comment