Custom DataAnnotation attribute to validate Password in MVC3 Razor


  1. Data Annotation attributes are used to validate the user inputs while posting the form.
  2. All the Data Annotation attributes like Required, Range are derived from ValidationAttribute class which is a abstract class.
  3. The ValidationAttribute base class lives in System.ComponentModel.DataAnnotations namespace.
  4. We can create our own Custom Annotation attribute which will have validation defined by us. 
  5. We have to inherit ValidationAttribute base class to create Custom Annotation attribute.
  6. In this article we will create Custom annotation attribute to validate Password.

ViewModel :


First we need to have a ViewModel in place where we will define our properties to render on UI. The ViewModel class looks like below :


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
  
namespace CustomValidation.Models
{
    public class Register
    {
        public string FirstName { get; set; }
  
        public string LastName { get; set; }
  
        public int Age { get; set; }
  
        public string Email { get; set; }
  
        public string Password { get; set; }
    }
}

The above is our ViewModel. We have defined properties we want on the form. We will pass this ViewModel to view. Currently we have not applied any DataAnnotation attribute to properties.

View :



@model CustomValidation.Models.Register

@{
    ViewBag.Title = "Register";
    Layout = null;
}



<h2 align="center">Register</h2>
@using (Html.BeginForm("Welcome","Register",new {@id = "formClass"}))
{
    <fieldset style="width:400px;">
    <legend>Registration Form</legend>
    @Html.EditorForModel("Register")
    <br /><br />
    <input type="submit" value="Submit" />
    </fieldset>
}

We have strongly binded the View with our ViewModel. We have created a form and used EditorForModel  HTML Helper to create controls for properties in the ViewModel. We have also created a Submit button to submit the form.

Custom DataAnnotation class for Password :



using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;

namespace CustomValidation.CustomValidator
{
    public class CustomPasswordValidator:ValidationAttribute
    {
        //Defined two private read only variables, to hold minimum and maximum length of password supplied using attribute definition.
        private readonly int minLen;
        private readonly int maxLen;

        //The constructor accepts two parameters. These parameters have to be supplied while applying this attribute.
        //We are also passing a default message to base class. This is default message.
        public CustomPasswordValidator(int minLength, int maxLength)
            : base("{0} length should be between " + minLength + " and " + maxLength + "")
        {
            minLen = minLength;
            maxLen = maxLength;

        }


        //We have override the IsValid method which accepts value and ValidationContext object.
        //value is the input provided by user from Form. The value which is posted from form.
        //Validation context object has details about the property on which this attribute is used.
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {

            //Validating user input.
            //The value is null, if the user leaves age field balnk on form.
            //We are returing error message in the else part of this if.
            //This check works like Required attribute.
            if (value != null)
            {
                //Converting the value to integer from object type.
                string userValue = value.ToString();

                //Comparing the length of password entered with the minimum limit.
                if (userValue.Length < minLen)
                {
                    //If the length of password is less than the applied length, validation message is thrown.
                    return new ValidationResult("Password cannot be less than 6 letters.");
                }
                //Comparing the length of password entered with the maximum limit.
                else if (userValue.Length > maxLen)
                {
                    //If the length of password is greater than the applied length, validation message is thrown.
                    return new ValidationResult("Password cannot be greater than 12 letters");
                }
                else
                {
                    //If the supplied password passes all the validations success result is returned.
                    return ValidationResult.Success;
                }
            }
            else
            {
                //If the user does not provide his password. The mandatory error message is shown.
                return new ValidationResult("Password is manadatory Field.");
            }
            
        }
    }
}

The above class validates the user's password. The user's password is validated against defined maximum and minimum limits i.e. number of words allowed. We have also validated the presence of user's input. If user leaves the age field blank, error message is thrown. 


How to apply :

[DataType(DataType.Password)]
[CustomPasswordValidator(6,12)]
public string Password { get; set; }


UI :




In the above case, we tried to enter password less than 6 letters. The validation attribute throws an error saying password cannot be less than 6 letters.


In the above case, we tried to enter password greater than 12 letters. The validation attribute throws an error saying password cannot be greater than 12 letters.



We have also validated user input for null or blank value. If user tries to leave password field blank, then validation attribute throws an error.

Thus we can include more validations in the same class. We can also verify whether a password contains special characters or not and many more validations.

0 comments:

Post a Comment