Skip to content

Injection of validators

remogloor edited this page Feb 12, 2011 · 2 revisions

Another new feature of the MVC3 extension is the support for injection of validation attributes. But as with all other attributes it only allows property injection. The following example demonstrates how to create a zip code validation attribute that uses a service to check if the value is valid and that the zip code exists.

public class ZipCodeAttribute : ValidationAttribute
{
    [Inject]
    public IZipCodeService ZipCodeService { get; set; }
 
    public override bool IsValid(object value)
    {
        if (value == null)
        {
            return true;
        }
 
        if ((value is string) && string.IsNullOrEmpty((string)value))
        {
            return true;
        }
 
        var zipCode = Convert.ToInt32(value);
        return this.ZipCodeService.IsValidZipCode(zipCode);
    }
}