Using Custom Validation Attributes in ASP.NET MVC


Model validations are required for ensuring that the received data we receive is valid and correct so that we can do the further processing with this data. We can validate a model in an action method. The built-in validation attributes are Compare, Range, RegularExpression, Required, StringLength. However we may have scenarios wherein we required validation attributes other than the built-in ones.

Custom Validation Attributes

Below is the code for the same, its pretty self-explanatory. In case of doubts or queries feel free to use the comments section.

public class EmployeeModel 
    public string EmailAddress {get;set;}
    public string FirstName {get;set;}
    public string LastName {get;set;}
    public int OrganizationId {get;set;}

To create a custom validation attribute, you will have to derive this class from ValidationAttribute.

public class UniqueEmailAddress : ValidationAttribute
    private IEmployeeRepository _employeeRepository;
    public IEmployeeRepository EmployeeRepository
        get { return _employeeRepository; }
            _employeeRepository = value;
    protected override ValidationResult IsValid(object value,
                        ValidationContext validationContext)
        var message = "Email address already in use in this organization.";
        var model = (EmployeeModel)validationContext.ObjectInstance;
        var spec = new Specification<EmployeeModel>
        (m => m.EmailAddress == value && m.OrganizationId == model.OrganizationId);
        var emp = _employeeRepository.Get(spec);
        if(emp != null)
            return new ValidationResult(message);
        return ValidationResult.Success;

Hope this helps. Cheers !