asp.net-mvc Custom Validation Attribute


Example

When it comes to validate some rules which are not generic data validation e.g ensuring a field is required or some range of values but they are specific to your business logic then you can create your own Custom Validator. To create a custom validation attribute, you just need to inherit ValidationAttribute class and override its IsValid method. The IsValid method takes two parameters, the first is an object named as value and the second is a ValidationContext object named as validationContext. Value refers to the actual value from the field that your custom validator is going to validate.

Suppose you want to validate Email through Custom Validator

public class MyCustomValidator : ValidationAttribute
{
    private static string myEmail= "admin@dotnetfiddle.net";

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        string Email = value.ToString();
        if(myEmail.Equals(Email))
            return new ValidationResult("Email Already Exist");
        return ValidationResult.Success;
    }
}

public class SampleViewModel
{
    [MyCustomValidator]
    [Required]
    public string Email { get; set; }

    public string Name { get; set; }
}

Here is its DotNetFiddle Demo