Custom DataAnnotation attribute to validate Email Address


  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 Email-Id.


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 Email Validator Class :



using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
//Namespace to use ValidationAttribute class
using System.ComponentModel.DataAnnotations;
//Name space to use regulsr expression.
using System.Text.RegularExpressions;

namespace CustomValidation.CustomValidator
{
    public class CustomEmailValidator : ValidationAttribute
    {
        //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 email = value.ToString();

                //Validating email id entered by the user against regular expression.
                if(Regex.IsMatch(email,@"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}"))
                {
                    //If email address is valid according to regular expression, suceess validation result is returned.
                   return  ValidationResult.Success;
                }
                else
                {
                    //If the email address is not accoring to the regular expression, error message is returned.
                    return new ValidationResult("Email Format is incorrect.");
                }
            }
            else
            {
                //If the user does not provide his age. The mandatory error message is shown.
                return new ValidationResult(""+ validationContext.DisplayName +" field is manadatory");
            }
        }
    }
}

The above class validates the user's email. The user's email is validated against regular expression. The error message is return if email does not matches the expression. We have also applied validation to check if email supplied by user is null or not.

How to apply :



[CustomEmailValidator]
public string Email { get; set; }

We applied our custom class to the email property in the ViewModel. CustomEmailValidator is the name of our class.

UI :




In the above screenshot I have entered email address which is not a proper address and also against our regular expression. The validation attribute class thrown error.


In the above screenshot, I have not supplied email address. The validation attribute class has thrown validation message.

We can customize the above class to have more validations and even customize the regular expression to support different formats of email addresses.


0 comments:

Post a Comment