Custom DataAnnotation attribute to validate Age or integer inputs


  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 integer inputs with their limits like AGE.


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 :


Our View looks like below :

@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 Age DataAnnotation class :




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

namespace CustomValidation.CustomValidator
{
    public class CustomAgeValidator : ValidationAttribute
    {
        //Defined two private read only variables, to hold minimum and maximum age supplied using attribute definition.
        private readonly int lowerLimit;
        private readonly int higherLimit;

        //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 CustomAgeValidator(int minAge, int maxAge)
            : base("{0} should be between " + minAge + " and " + maxAge + "")
        {
            lowerLimit = minAge;
            higherLimit = maxAge;
        }

        //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)
        {
          //Converting the value to integer from object type.
            int userValue = Convert.ToInt32(value);
//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)
            {
                //Here we are validating whether the user age is according to the accepted limits.
                if (userValue >= lowerLimit && userValue <= higherLimit)
                {
                    //We return success validation result, if the age is in limit.
                    return ValidationResult.Success;
                }
                else
                {
                    //If the user's age is not within the accepted limits error message is returned.
                    //As we have passed the default message above. We have passed a placeholder with it.
                    //The display name is passed as parameter. And error message is displayed.
                    var errorMessage = FormatErrorMessage(validationContext.DisplayName);
                    return new ValidationResult(errorMessage);
                }
            }
            else
            {
                //If the user does not provide his age. The mandatory error message is shown.
                return new ValidationResult("Age is manadatory Field");
            }
             
        }

    }
}

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

How to apply :



[CustomAgeValidator(20, 40)]
public int Age { get; set; }

The CustomAgeValidator is the name of class. We are passing minimum and maximum age limit as 20 and 40.

UI : 



The validator throws error when user supplied age not between 20 and 40.



The validator also throws error when user leaves the age field blank. This works similar to the Required DataAnnotation attribute. 
In the same manner we can apply as many as validation we want by creating Custom Annotation attributes.



0 comments:

Post a Comment