February 8, 2014

Custom Validation in ASP.Net MVC 4



To implement custom validation in C# ASP.NET MVC4, it needs to inherit “ValidationAttribute” class and overwrite “IsValid” method in your class. For this you need to add namespace System.ComponentModel.DataAnnotations.

Here, I am creating a class for my custom password attributes and its minimum length should be of 5 chars and maximum  length should be of 10 chars. I have initialized the values in its constructor and defined the code logic in overridden method “IsValid”.

public class PasswordAttribute : ValidationAttribute
{
            int MinLength;
            int MaxLength;

public PasswordAttribute(int minLength, int maxLength)
        {
            this.MinLength = minLength;
            this.MaxLength = maxLength;
        }

            public override bool IsValid(object value)
       {
            // TODO:
                     if (condition_satisfied)
                return true;
            else
                return false;
            }
}

Use the class to validate password value:

 public class SetUserPassword
 {
   [Required(ErrorMessage = "Please enter a password.", AllowEmptyStrings = false)]
   [Password(5, 10, ErrorMessage = "Please enter 5-10 digits password.")]
   public string Password { get; set; }

  }


ASP.Net MVC 4 provides four types of validations:
1. Required – To check for required field.
2. Range- To check for lower and upper limits.
3. Regular expression- To check for an expression.
4. Custom validation- User defined validation.
MVC4 does not provide Compare validation as in previous ASPX web forms. If you wish to use compare validation, either you may need to use the available DLL or go for custom validation.