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; }

  }


For ActionResult attribute, you must inherit ActionFilterAttribute class and override respective base method, as per your need. ActionFilterAttribute resides in namespace System.Web.Mvc. Here, I am overriding OnActionExecuting method that executes while execution of an action.

public class CheckUserSessionAttribute : ActionFilterAttribute
  {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            HttpCookie ck = HttpContext.Current.Request.Cookies["user"];
            if (ck == null || string.IsNullOrEmpty(ck.Value))
                filterContext.Result = new RedirectResult("home/login");
        }
  }


[HttpGet]
[CheckUserSession]
 public ActionResult Index()
{
      return View();
}



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.

Comments

Popular posts from this blog

A new threat to users on “Incoming Calls” – VISHING

Session Storage - a client-side state management technique

HTTP Error 500.21 - Internal Server Error: ExtensionlessUrlHandler-ISAPI-4.0_32 bit has a bad module