Custom Validation Attribute In ASP.NET MVC

Introduction

 
In this article, we will discuss custom validation with example in ASP.NET MVC.
 
Step 1
 
Open Visual Studio 2015 or a version of your choice and create a project.
 
Step 2
 
Choose a "web application" project and give an appropriate name to your project.
 
Custom Validation Attribute In ASP.NET MVC
 
Step 3
 
Select the "empty" template, check on the MVC, and click OK.
 
Custom Validation Attribute In ASP.NET MVC
 
Step 4
 
Right-click on Models folder, choose “Add”, then choose the class. Name it as Employee.cs.
 
Custom Validation Attribute In ASP.NET MVC
 
After clicking on class, another window pops up. Select class, name it as Employee, and click on “Add”.
 
Custom Validation Attribute In ASP.NET MVC
 
Employee Class
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.ComponentModel.DataAnnotations;  
  4. using System.Linq;  
  5. using System.Web;  
  6. using MvcCustomValidationAttribute_Demo.CustomValidation;  
  7.   
  8. namespace MvcCustomValidationAttribute_Demo.Models  
  9. {  
  10.     public class Employee  
  11.     {  
  12.         public int Id { getset; }  
  13.   
  14.         [Required(ErrorMessage = "Please enter name")]  
  15.         public string Name { getset; }  
  16.   
  17.         [Required(ErrorMessage = "Please enter position")]  
  18.         public string Position { getset; }  
  19.   
  20.         [Required(ErrorMessage = "Please enter office")]  
  21.         public string Office { getset; }  
  22.   
  23.         [Required(ErrorMessage = "Please enter hire date")]  
  24.         [Display(Name = "Hire Date")]  
  25.         [DisplayFormat(DataFormatString = "{0:d}",ApplyFormatInEditMode = true)]  
  26.         [CustomHireDate(ErrorMessage = "Hire Date must be less than or equal to Today's Date")]  
  27.         public DateTime HireDate { getset; }  
  28.   
  29.         [Required(ErrorMessage = "Please enter salary")]  
  30.         public int Salary { getset; }    
  31.     }  
  32. }  
Step 5
 
Right-click on the project and select “Add Folder”, name it Custom Validation, and add class with name CustomHireDate. Now, write the following code in it.
 
Custom Validation Class Code
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.ComponentModel.DataAnnotations;  
  4. using System.Linq;  
  5. using System.Web;  
  6. using System.Web.Mvc;  
  7.   
  8. namespace MvcCustomValidationAttribute_Demo.CustomValidation  
  9. {  
  10.     public class CustomHireDate:ValidationAttribute  
  11.     {  
  12.         public override bool IsValid(object value)  
  13.         {  
  14.             DateTime dateTime = Convert.ToDateTime(value);  
  15.             return dateTime <= DateTime.Now;  
  16.         }  
  17.     }  
  18. }  
Step 6
 
Right-click on the Controllers folder and add a new controller.
 
Custom Validation Attribute In ASP.NET MVC
 
A window will appear. Choose MVC5 Controller-Empty and click "Add".
 
Custom Validation Attribute In ASP.NET MVC
 
After clicking on "Add", another window will appear with DefaultController. Change the name to HomeController and click "Add". The HomeController will be added under the Controllers folder. Don’t change the Controller suffix for all controllers, change only the highlight, and instead of Default, just change Home.
 
Custom Validation Attribute In ASP.NET MVC
 
Home Controller Code
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6. using MvcCustomValidationAttribute_Demo.Models;  
  7.   
  8. namespace MvcCustomValidationAttribute_Demo.Controllers  
  9. {  
  10.     public class HomeController : Controller  
  11.     {  
  12.         // GET: Home  
  13.         public ActionResult Index()  
  14.         {  
  15.             return View();  
  16.         }  
  17.   
  18.         [HttpGet]  
  19.         public ActionResult Create()  
  20.         {  
  21.             return View();  
  22.         }  
  23.   
  24.         [HttpPost]  
  25.         [ValidateAntiForgeryToken]  
  26.         public ActionResult Create(Employee employee)  
  27.         {  
  28.             if (ModelState.IsValid)  
  29.             {  
  30.                 RedirectToAction("Index");  
  31.             }  
  32.   
  33.             return View();  
  34.         }  
  35.     }  
  36. }  
Step 7
 
Right-click on Index method in HomeController. The "Add View" window will appear with the default index name checked (use a Layout page). Here, click on "Add.
 
Create View Code
  1. @model MvcCustomValidationAttribute_Demo.Models.Employee  
  2.   
  3. @{  
  4.     ViewBag.Title = "Create";  
  5. }  
  6.   
  7. @using (Html.BeginForm())   
  8. {  
  9.     @Html.AntiForgeryToken()  
  10.       
  11.     <div class="form-horizontal">  
  12.         <h4>Create Employee</h4>  
  13.         <hr />  
  14.         @Html.ValidationSummary(true""new { @class = "text-danger" })  
  15.         <div class="form-group">  
  16.             @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })  
  17.             <div class="col-md-10">  
  18.                 @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })  
  19.                 @Html.ValidationMessageFor(model => model.Name)  
  20.             </div>  
  21.         </div>  
  22.   
  23.         <div class="form-group">  
  24.             @Html.LabelFor(model => model.Position, htmlAttributes: new { @class = "control-label col-md-2" })  
  25.             <div class="col-md-10">  
  26.                 @Html.EditorFor(model => model.Position, new { htmlAttributes = new { @class = "form-control" } })  
  27.                 @Html.ValidationMessageFor(model => model.Position)  
  28.             </div>  
  29.         </div>  
  30.   
  31.         <div class="form-group">  
  32.             @Html.LabelFor(model => model.Office, htmlAttributes: new { @class = "control-label col-md-2" })  
  33.             <div class="col-md-10">  
  34.                 @Html.EditorFor(model => model.Office, new { htmlAttributes = new { @class = "form-control" } })  
  35.                 @Html.ValidationMessageFor(model => model.Office)  
  36.             </div>  
  37.         </div>  
  38.   
  39.         <div class="form-group">  
  40.             @Html.LabelFor(model => model.HireDate, htmlAttributes: new { @class = "control-label col-md-2" })  
  41.             <div class="col-md-10">  
  42.                 @Html.EditorFor(model => model.HireDate, new { htmlAttributes = new { @class = "form-control" } })  
  43.                 @Html.ValidationMessageFor(model => model.HireDate)  
  44.             </div>  
  45.         </div>  
  46.   
  47.         <div class="form-group">  
  48.             @Html.LabelFor(model => model.Salary, htmlAttributes: new { @class = "control-label col-md-2" })  
  49.             <div class="col-md-10">  
  50.                 @Html.EditorFor(model => model.Salary, new { htmlAttributes = new { @class = "form-control" } })  
  51.                 @Html.ValidationMessageFor(model => model.Salary)  
  52.             </div>  
  53.         </div>  
  54.   
  55.         <div class="form-group">  
  56.             <div class="col-md-offset-2 col-md-10">  
  57.                 <input type="submit" value="Create" class="btn btn-default" />  
  58.             </div>  
  59.         </div>  
  60.     </div>  
  61. }  
Step 8
 
Build and run the project by pressing ctrl+F5.
 
Custom Validation Attribute In ASP.NET MVC


Similar Articles