Injection of validators

Remo Gloor edited this page Feb 23, 2012 · 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);
    }
}
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Press h to open a hovercard with more details.