MVC 4: Custom Validation Data Annotation Attribute

Data Annotations

Validation in MVC can be done using Data Annotations that are applied to both the client and server side.

Data Annotation attributes are used to validate the user inputs when posting the form. All the Data Annotation attributes like Required, Range are derived from the ValidationAttribute class that is an abstract class. The ValidationAttribute base class lives in the System.ComponentModel.DataAnnotations namespace.

This article is showing how to create a custom Data Annotations step by step:

Step 1

Create a New MVC 4 Application.

Step 2

Select Razor View Engine.

Step 3

Here I am showing Email validation on the Employee Registration Form.

Select the Model Folder then select Add New Item -> Add New Class CustomEmailValidator.cs.

Here we need to inherit the ValidationAttribute and need to override the IsValid method.

CustomEmailValidator.cs

  1. using System;    
  2. using System.Collections.Generic;    
  3. using System.Linq;    
  4. using System.Web;    
  5. using System.ComponentModel.DataAnnotations;    
  6. using System.Text.RegularExpressions;    
  7.     
  8. namespace Custom_DataAnnotation_Attribute.Models    
  9. {    
  10.     public class CustomEmailValidator : ValidationAttribute    
  11.     {    
  12.         protected override ValidationResult IsValid(object value, ValidationContext validationContext)    
  13.         {    
  14.             if (value != null)    
  15.             {    
  16.                 string email = value.ToString();    
  17.     
  18.                 if (Regex.IsMatch(email, @"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}", RegexOptions.IgnoreCase))    
  19.                 {    
  20.                     return ValidationResult.Success;    
  21.                 }    
  22.                 else    
  23.                 {    
  24.                     return new ValidationResult("Please Enter a Valid Email.");    
  25.                 }    
  26.             }    
  27.             else    
  28.             {    
  29.                 return new ValidationResult("" + validationContext.DisplayName + " is required");    
  30.             }    
  31.         }  
  32.     }  
  33. } 
Step 4 Right-click on the Model Folder then select Add New Item -> Add New Class -> EmployeeModel.cs.
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.ComponentModel.DataAnnotations;
  6.     
  7. namespace Custom_DataAnnotation_Attribute.Models
  8. {
  9.     public class EmployeeModel
  10.     {
  11.         public string Name { getset; }
  12.     
  13.         [CustomEmailValidator]
  14.         public string Email { getset; }
  15.         public string Password { getset; }
  16.         public string Mobile { getset; }
  17.     }
  18. }
Here you can see we are using [CustomEmailValidator] in the preceding Email.

Step 5 Now right-click on the Controller Folder then select Add New Controller.

controller
Image 1

Here in ManageEmployeeController I added a new Index Action.
  1. using System;    
  2. using System.Collections.Generic;    
  3. using System.Linq;    
  4. using System.Web;    
  5. using System.Web.Mvc;    
  6. using Custom_DataAnnotation_Attribute.Models;    
  7.     
  8. namespace Custom_DataAnnotation_Attribute.Controllers    
  9. {    
  10.     public class ManageEmployeeController : Controller    
  11.     {    
  12.         //    
  13.         // GET: /ManageEmployee/    
  14.     
  15.         public ActionResult Index()    
  16.         {    
  17.             return View();    
  18.         }    
  19.     
  20.         [AcceptVerbs(HttpVerbs.Post)]    
  21.         public ActionResult Index(EmployeeModel model)    
  22.         {    
  23.             if (ModelState.IsValid)    
  24.             {    
  25.                 ViewBag.Name = model.Name;    
  26.                 ViewBag.Email = model.Email;    
  27.                 ViewBag.Password = model.Password;    
  28.                 ViewBag.Mobile = model.Mobile;    
  29.             }    
  30.             return View(model);    
  31.         }    
  32.     
  33.         public ActionResult Register()    
  34.         {    
  35.             return View();    
  36.         }    
  37.     
  38.     }    
  39. }  
Step 6 Now right-click on the Index Action then select Add View.

view
Image 2

Step 7 Now the ManageEmployee's index.cshtml file will look like:
  1. @model Custom_DataAnnotation_Attribute.Models.EmployeeModel  
  2.   
  3. @{  
  4.     ViewBag.Title = "Register Employee";  
  5.        
  6. }  
  7.   
  8. <h2>Register</h2>  
  9.   
  10. @using (Html.BeginForm()) {  
  11.     @Html.ValidationSummary(true)  
  12.   
  13.     <fieldset>  
  14.         <legend>EmployeeModel</legend>  
  15.   
  16.         <div class="editor-label">  
  17.             @Html.LabelFor(model => model.Name)  
  18.         </div>  
  19.         <div class="editor-field">  
  20.             @Html.EditorFor(model => model.Name)  
  21.             @Html.ValidationMessageFor(model => model.Name)  
  22.         </div>  
  23.   
  24.         <div class="editor-label">  
  25.             @Html.LabelFor(model => model.Email)  
  26.         </div>  
  27.         <div class="editor-field">  
  28.             @Html.EditorFor(model => model.Email)  
  29.             @Html.ValidationMessageFor(model => model.Email)  
  30.         </div>  
  31.   
  32.         <div class="editor-label">  
  33.             @Html.LabelFor(model => model.Password)  
  34.         </div>  
  35.         <div class="editor-field">  
  36.             @Html.EditorFor(model => model.Password)  
  37.             @Html.ValidationMessageFor(model => model.Password)  
  38.         </div>  
  39.   
  40.         <div class="editor-label">  
  41.             @Html.LabelFor(model => model.Mobile)  
  42.         </div>  
  43.         <div class="editor-field">  
  44.             @Html.EditorFor(model => model.Mobile)  
  45.             @Html.ValidationMessageFor(model => model.Mobile)  
  46.         </div>  
  47.   
  48.         <p>  
  49.             <input type="submit" value="Create" />  
  50.         </p>  
  51.     </fieldset>  
  52. }  
  53.   
  54. <div>  
  55.     @Html.ActionLink("Back to List""Index")  
  56. </div>  
  57.   
  58. @section Scripts {  
  59.     @Scripts.Render("~/bundles/jqueryval")  
  60. }

Now run the application:

email is require
Image 3

output
Image 4


Similar Articles