Custom Data Annotation attribute to validate string inputs like Name.



  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 string inputs like name.



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

We have created a Register class with some properies. This properties are used to bind the form and render the controls.



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 used EditorForModel helper to render the form.



Custom Name attribute class :


We have created a separate folder to include class files. The class file for Custom Annotation Attribute looks like below :




using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
//We have include the below namespace to use DataAnnotations
using System.ComponentModel.DataAnnotations;

namespace CustomValidation.CustomNameValidator
{
    //Inherited the base class ValidationAttribute to create our own Custom Attribute.
    public class CustomNameValidator : ValidationAttribute
    {
        private readonly int maxWords;

        //The constructor accepts single parameter i.e. maximum limit  to check the count of words. 
        //This can be used to validate FirstName to have specified number of words.
        //We are also passing a default message to base class. This is default message. 
        public CustomNameValidator(int maximumLimit)
            : base("{0} should be less than " + maximumLimit + " letters.")
        {
            //We are setting a private variable MaxWords with maximum limit which is specified while defining attribute.
            maxWords = maximumLimit;
        }

        //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)
        {
            //Checking if the value is null.
            if (value != null)
            {
                //casting the object value to string.
                var valueAsString = value.ToString();
                //comparing the input value length and the length specified while defining attributes.
                if (valueAsString.Length < maxWords)
                {
                    //If the input length is within the maximum length allowed then attribute will return Success.
                    return ValidationResult.Success;
                }
                else
                {
                    //If the input length is not withing the maximum length, then 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 value is null, we are returning error message. This validation works like Required attribute.
                //In below line we are passing display name and message as well.
                return new ValidationResult("" + validationContext.DisplayName + " is manadatory field");
            }
        }
    }
}


The above code validates the string input. It validates the input for its count. It also checks if value is null or not. The code returns the error message if validation fails.



How to apply :




        [CustomNameValidator.CustomNameValidator(40)]
        public string LastName { get; set; }

As per the above definition, the maximum string length allowed for LastName property is 40. If the value is more than 40, validation fails and error message is shown.



UI :


The validation message is shown if Last name length increases above 40.


1 comments:

  1. Nice way to validate string inputs using DataAnnotation. Thanks for this nice article.

    ReplyDelete