Model Validation In MVC 5

Introduction

There are several validation attributes available in MVC 5 and we can create our custom validation also by overriding the ValidationAttribute method.

What are validations?

We can say that validation is nothing but some rules set by the developer on the input fields of a web page so as to satisfy the business rules for that particular input field in order to maintain proper data in the system.

What are the types of validation?

There are two types of validation.

  1. Server-side Validation
  2. Client Side Validation

The System.ComponentModel.DataAnnotations assembly has many built-in validation attributes.

  • Required
  • Range
  • RegularExpression,
  • Compare
  • StringLength
  • Data type
  • Credit Card number
  • Currency
  • Custom
  • Date
  • DateTime
  • Duration
  • Email Address
  • HTML
  • Image URL
  • Multiline text
  • Password
  • Phone number
  • Postal Code
  • Upload

Step 1

Open Visual Studio 2015 or an IDE of your choice and create a new project.

Step 2

Choose web application project and give an appropriate name to your project.
 
Model Validation In MVC 5 

Step 3

Select the empty template, check on MVC checkbox below, and click OK.
 
Model Validation In MVC 5 

Step 4

Right-click on the Models folder and add a class. Name it as employee.
 
Model Validation In MVC 5 

You will get a window; from there, select class, name it Employee, and click "Add".

Model Validation In MVC 5
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.ComponentModel.DataAnnotations;  
  4. using System.Linq;  
  5. using System.Web;  
  6.    
  7. namespace MvcModelValidation_Demo.Models  
  8. {  
  9.     public class Employee  
  10.     {  
  11.         public int Id { getset; }  
  12.    
  13.         [Required(ErrorMessage = "Enter first name")]  
  14.         [Display(Name = "First Name")]  
  15.         public string FirstName { getset; }  
  16.    
  17.         [Required(ErrorMessage = "Enter last name")]  
  18.         [Display(Name = "Last Name")]  
  19.         public string LastName { getset; }  
  20.    
  21.         [Required(ErrorMessage = "Choose your gender")]  
  22.         public string Gender { getset; }  
  23.    
  24.         [Required(ErrorMessage = "Choose date of birth")]  
  25.         [Display(Name = "Date of Birth")]  
  26.         [DataType(DataType.Date)]  
  27.         public DateTime BirthDate { getset; }  
  28.          
  29.    
  30.         [Required(ErrorMessage = "Enter phone number")]  
  31.         [Phone]  
  32.         [Display(Name = "Phone Number")]  
  33.         public string PhoneNumber { getset; }  
  34.    
  35.         [Required(ErrorMessage = "Enter your email address")]  
  36.         [EmailAddress]  
  37.         public string Email { getset; }  
  38.    
  39.         [Required(ErrorMessage = "Enter your address")]  
  40.         public string Address { getset; }  
  41.    
  42.         [Required(ErrorMessage = "Enter your position")]  
  43.         public string Position { getset; }  
  44.    
  45.         [Required(ErrorMessage = "Enter you salary")]  
  46.         public int Salary { getset; }  
  47.           
  48.     }  
  49. }  

Step 5

Right-click on the Controllers folder and choose Add >> Controller.
 
Model Validation In MVC 5 

A window will appear. Choose MVC5 Controller-Empty and click "Add".

Model Validation In MVC 5 

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;

Model Validation In MVC 5 

Complete code for Home Controller

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6. using MvcModelValidation_Demo.Models;  
  7.    
  8. namespace MvcModelValidation_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.         public ActionResult Create(Employee employee)  
  26.         {  
  27.             try  
  28.             {  
  29.                 if (ModelState.IsValid)  
  30.                 {  
  31.                    return RedirectToAction("Index");  
  32.                 }  
  33.    
  34.                 return View();  
  35.             }  
  36.             catch (Exception)  
  37.             {  
  38.                 return View();  
  39.             }  
  40.         }  
  41.     }  
  42. }  

Step 6

Right click on Index method in HomeController The "Add View" window will appear with default index name checked (use a Layout page), and click on "Add.

Model Validation In MVC 5
  1. @model MvcModelValidation_Demo.Models.Employee  
  2. @{  
  3.     ViewBag.Title = "Create";  
  4. }  
  5. @section Styles {  
  6.     <link href="https://cdn.jsdelivr.net/npm/[email protected]/css/gijgo.min.css" rel="stylesheet" type="text/css" />  
  7. }  
  8. @using (@Html.BeginForm())  
  9. {  
  10.     <div class="card" style="width: 65%; margin:auto;">  
  11.         <div class="card-header bg-primary">  
  12.             <h5 class="text-white text-center text-uppercase">Employee Information Form</h5>  
  13.         </div>  
  14.         <div class="card-body">  
  15.             <div class="row">  
  16.                 <div class="col-md-6">  
  17.                     <div class="form-group">  
  18.                         @Html.LabelFor(m => m.FirstName)  
  19.                         @Html.TextBoxFor(m => m.FirstName, new { @class = "form-control",maxlength="30" })  
  20.                         @Html.ValidationMessageFor(m => m.FirstName)  
  21.                     </div>  
  22.                 </div>  
  23.                 <div class="col-md-6">  
  24.                     <div class="form-group">  
  25.                         @Html.LabelFor(m => m.LastName)  
  26.                         @Html.TextBoxFor(m => m.LastName, new { @class = "form-control" })  
  27.                         @Html.ValidationMessageFor(m => m.LastName)  
  28.                     </div>  
  29.                 </div>  
  30.             </div>  
  31.             <div class="row">  
  32.                 <div class="col-md-6">  
  33.                     <div class="form-group">  
  34.                         @Html.LabelFor(m => m.Gender)  
  35.                         @Html.DropDownList("Gender"new List<SelectListItem>()  
  36.                 {  
  37.                     new SelectListItem {Text = "Male", Value = "1"},  
  38.                     new SelectListItem {Text = "Female", Value = "2"}  
  39.                 }, "Choose Gender"new { @class = "form-control" })  
  40.                         @Html.ValidationMessageFor(m => m.Gender)  
  41.                     </div>  
  42.                 </div>  
  43.                 <div class="col-md-6">  
  44.                     <div class="form-group">  
  45.                         @Html.LabelFor(m => m.BirthDate)  
  46.                         @Html.TextBox("BirthDate"""new { @class = "form-control", @readonly = "readonly" })  
  47.                         @Html.ValidationMessageFor(m => m.BirthDate)  
  48.                     </div>  
  49.                 </div>  
  50.             </div>  
  51.             <div class="row">  
  52.                 <div class="col-md-6">  
  53.                     <div class="form-group">  
  54.                         @Html.LabelFor(m => m.PhoneNumber)  
  55.                         @Html.TextBoxFor(m => m.PhoneNumber, new { @class = "form-control" })  
  56.                         @Html.ValidationMessageFor(m => m.PhoneNumber)  
  57.                     </div>  
  58.                 </div>  
  59.                 <div class="col-md-6">  
  60.                     <div class="form-group">  
  61.                         @Html.LabelFor(m => m.Email)  
  62.                         @Html.TextBoxFor(m => m.Email, new { @class = "form-control" })  
  63.                         @Html.ValidationMessageFor(m => m.Email)  
  64.                     </div>  
  65.                 </div>  
  66.             </div>  
  67.             <div class="row">  
  68.                 <div class="col-md-6">  
  69.                     <div class="form-group">  
  70.                         @Html.LabelFor(m => m.Position)  
  71.                         @Html.TextBoxFor(m => m.Position, new { @class = "form-control" })  
  72.                         @Html.ValidationMessageFor(m => m.Position)  
  73.                     </div>  
  74.                 </div>  
  75.                 <div class="col-md-6">  
  76.                     <div class="form-group">  
  77.                         @Html.LabelFor(m => m.Salary)  
  78.                         @Html.TextBoxFor(m => m.Salary, new { @class = "form-control" })  
  79.                         @Html.ValidationMessageFor(m => m.Salary)  
  80.                     </div>  
  81.                 </div>  
  82.             </div>  
  83.             <div class="row">  
  84.                 <div class="col-md-12">  
  85.                     <div class="form-group">  
  86.                         @Html.LabelFor(m => m.Address)  
  87.                         @Html.TextAreaFor(m => m.Address, new { @class = "form-control", rows = "5" })  
  88.                         @Html.ValidationMessageFor(m => m.Address)  
  89.                     </div>  
  90.                 </div>  
  91.             </div>  
  92.             <button type="submit" class="btn btn-primary">Submit</button>  
  93.         </div>  
  94.     </div>  
  95. }  
  96.    
  97. @section Scripts {  
  98.     <script src="https://cdn.jsdelivr.net/npm/[email protected]/js/gijgo.min.js" type="text/javascript"></script>  
  99.     <script>  
  100.         $('#BirthDate').datepicker({  
  101.             uiLibrary: 'bootstrap4'  
  102.         });  
  103.     </script>  
  104. }  

Step 7

Download jquery.validate.unobtrusive and jquery.validate packages from NuGet Package Manager. Open Views folder, under shared folder, click on _Layout file. Add below files.
  1. <script src="~/scripts/jquery-3.3.1.min.js"></script>  
  2. <script src="~/scripts/jquery.validate.min.js"></script>  
  3. <script src="~/scripts/jquery.validate.unobtrusive.min.js"></script>  
  4. <script src="~/Scripts/bootstrap.min.js"></script>  
  5. @RenderSection("Scripts"true)  
  6. @RenderSection(name: "Styles",required:true)  

Complete code for _Layout.csthml

  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4.     <meta charset="utf-8" />  
  5.     <meta name="viewport" content="width=device-width, initial-scale=1.0">  
  6.     <title>@ViewBag.Title - My ASP.NET Application</title>  
  7.     <link href="~/Content/Site.css" rel="stylesheet" type="text/css" />  
  8.     <link href="~/Content/bootstrap.min.css" rel="stylesheet" type="text/css" />  
  9. </head>  
  10. <body>  
  11. <div class="container">  
  12.     @RenderBody()  
  13. </div>  
  14. <script src="~/scripts/jquery-3.3.1.min.js"></script>  
  15. <script src="~/scripts/jquery.validate.min.js"></script>  
  16. <script src="~/scripts/jquery.validate.unobtrusive.min.js"></script>  
  17. <script src="~/Scripts/bootstrap.min.js"></script>  
  18. @RenderSection("Scripts"true)  
  19. @RenderSection(name: "Styles",required:true)  
  20. </body>  
  21. </html>  

Step 8

Build and run your project by ctrl and F5.
Model Validation In MVC 5
 
Model Validation In MVC 5


Similar Articles