Model Validation In ASP.NET MVC Core 3.1

In this article we will understand the concept of model validation in ASP.NET MVC core 3.1. It is valid for any version of MVC core. These validations are available in System.ComponentModel.DataAnnotations namespace. Validation attributes let us specify validation rules for model properties. Model state represents errors that come from two sub systems' model binding and model validation.
 
There are in-built attributes in ASP.NET MVC core,
 
Attribute
Description
CreditCard
This validates that the property has a credit card format.
Compare
This attribute validates that two property in model class match like password and compare password.
EmailAddress
This validates the property has email address format.
Phone
This validates that the property has a telephone number format.
Range
This validates that the property value within a specified range.
RegularExpression
This validates that the property value matches a specified regular expression.
Required
This validates that the field is not null
StringLength
This validates that a string property value doesn't exceed a specified length limit.
Url
This validates that the property has a URL format.
Remote
This validates input on the client by calling an action method on the server
 
Step 1
 
Start-up Visual Studio 2019. Now click on create new project and Choose ASP.NET Core Web Application and click on “Next”
 
Model Validation In ASP.NET MVC Core 3.1
 
After clicking next, another wizard will open. Under the project name, give a meaningful name to your project and click on create.
 
Model Validation In ASP.NET MVC Core 3.1
 
That will open up another new wizard. Select ASP.Net Core 3.0 from the dropdown. If not, select default. Choose Web Application (Model-View-Controller) template and click on create which will create ASP.Net Core Application.
 
Model Validation In ASP.NET MVC Core 3.1
 
Step 2
 
Now right click on Models folder and “Add” class and name it Student.
  1. using System;    
  2. using System.ComponentModel.DataAnnotations;    
  3.     
  4. namespace MvcCoreModelValidation_Demo.Models    
  5. {    
  6.     public class Student    
  7.     {    
  8.         [Key]    
  9.         public int Id { getset; }    
  10.     
  11.         [Required(ErrorMessage = "Please enter name")]    
  12.         [StringLength(100)]    
  13.         public string Name { getset; }    
  14.     
  15.         [Required(ErrorMessage = "Please choose gender")]    
  16.         public string Gender { getset; }    
  17.     
  18.         [Required(ErrorMessage = "Please enter date of birth")]    
  19.         [Display(Name = "Date of Birth")]    
  20.         [DataType(DataType.Date)]    
  21.         public DateTime DateofBirth { getset; }    
  22.     
  23.         [Required(ErrorMessage = "Choose batch time")]  
  24.         [Display(Name = "Batch Time")]  
  25.         [DataType(DataType.Time)]   
  26.         public DateTime BatchTime { getset; }   
  27.     
  28.         [Required(ErrorMessage = "Please enter phone number")]    
  29.         [Display(Name = "Phone Number")]    
  30.         [Phone]    
  31.         public string PhoneNumber { getset; }    
  32.     
  33.         [Required(ErrorMessage = "Please enter email address")]  
  34.         [Display(Name = "Email Address")]   
  35.         [EmailAddress]   
  36.         public string Email { getset; }  
  37.     
  38.         [Required(ErrorMessage = "Please enter website url")]    
  39.         [Display(Name = "Website Url")]    
  40.         [Url]    
  41.         public string WebSite { getset; }    
  42.     
  43.         [Required(ErrorMessage = "Please enter password")]    
  44.         [DataType(DataType.Password)]    
  45.         public string Password { getset; }    
  46.     
  47.         [Required(ErrorMessage = "Please enter confirm password")]    
  48.         [Display(Name = "Confirm Password")]    
  49.         [Compare("Password", ErrorMessage = "Password and confirm password does not match")]    
  50.         public string ConfirmPassword { getset; }    
  51.     }    
  52. }    
Step 3
 
Now open HomeController which is added when we created new project. Write the following code for Index and New IActionResult methods.
  1. using Microsoft.AspNetCore.Mvc;  
  2. using MvcCoreModelValidation_Demo.Models;  
  3.   
  4. namespace MvcCoreModelValidation_Demo.Controllers  
  5. {  
  6.     public class HomeController : Controller  
  7.     {  
  8.         public IActionResult Index()  
  9.         {  
  10.             return View();  
  11.         }  
  12.   
  13.         [HttpPost]  
  14.         [ValidateAntiForgeryToken]  
  15.         public IActionResult Index(Student student)  
  16.         {  
  17.             if (ModelState.IsValid)  
  18.             {  
  19.   
  20.             }  
  21.             return View();  
  22.         }  
  23.   
  24.     }  
  25. }  
Step 4
 
Right click on Index IActionResult method. “Add” view with default name “Index” if you don’t have it. Write the following code.
  1. @model MvcCoreModelValidation_Demo.Models.Student  
  2.   
  3. @{  
  4.     ViewData["Title"] = "Home Page";  
  5. }  
  6.   
  7. <div class="card">  
  8.     <div class="card-header bg-primary text-white text-uppercase">  
  9.         <h4>Student Information</h4>  
  10.     </div>  
  11.     <div class="card-body">  
  12.         <form asp-action="Index">  
  13.             <div class="row">  
  14.                 <div class="col-md-6">  
  15.                     <div class="form-group">  
  16.                         <label asp-for="Name" class="lable-control"></label>  
  17.                         <input asp-for="Name" class="form-control" />  
  18.                         <span asp-validation-for="Name" class="text-danger"></span>  
  19.                     </div>  
  20.                 </div>  
  21.                 <div class="col-md-6">  
  22.                     <div class="form-group">  
  23.                         <label asp-for="Gender" class="lable-control"></label>  
  24.                         <select class="custom-select">  
  25.                             <option value="">Choose Gender</option>  
  26.                             <option value="Male">Male</option>  
  27.                             <option value="Female">Female</option>  
  28.                         </select>  
  29.                         <span asp-validation-for="Gender" class="text-danger"></span>  
  30.                     </div>  
  31.                 </div>  
  32.             </div>  
  33.             <div class="row">  
  34.                 <div class="col-md-6">  
  35.                     <div class="form-group">  
  36.                         <label asp-for="DateofBirth" class="lable-control"></label>  
  37.                         <input asp-for="DateofBirth" class="form-control" />  
  38.                         <span asp-validation-for="DateofBirth" class="text-danger"></span>  
  39.                     </div>  
  40.                 </div>  
  41.                 <div class="col-md-6">  
  42.                     <div class="form-group">  
  43.                         <label asp-for="BatchTime" class="lable-control"></label>  
  44.                         <input asp-for="BatchTime" class="form-control" />  
  45.                         <span asp-validation-for="BatchTime" class="text-danger"></span>  
  46.                     </div>  
  47.                 </div>  
  48.             </div>  
  49.             <div class="row">  
  50.                 <div class="col-md-4">  
  51.                     <div class="form-group">  
  52.                         <label asp-for="PhoneNumber" class="lable-control"></label>  
  53.                         <input asp-for="PhoneNumber" class="form-control" />  
  54.                         <span asp-validation-for="PhoneNumber" class="text-danger"></span>  
  55.                     </div>  
  56.                 </div>  
  57.                 <div class="col-md-4">  
  58.                     <div class="form-group">  
  59.                         <label asp-for="Email" class="lable-control"></label>  
  60.                         <input asp-for="Email" class="form-control" />  
  61.                         <span asp-validation-for="Email" class="text-danger"></span>  
  62.                     </div>  
  63.                 </div>  
  64.                 <div class="col-md-4">  
  65.                     <div class="form-group">  
  66.                         <label asp-for="WebSite" class="lable-control"></label>  
  67.                         <input asp-for="WebSite" class="form-control" />  
  68.                         <span asp-validation-for="WebSite" class="text-danger"></span>  
  69.                     </div>  
  70.                 </div>  
  71.             </div>  
  72.             <div class="row">  
  73.                 <div class="col-md-6">  
  74.                     <div class="form-group">  
  75.                         <label asp-for="Password" class="lable-control"></label>  
  76.                         <input asp-for="Password" class="form-control" />  
  77.                         <span asp-validation-for="Password" class="text-danger"></span>  
  78.                     </div>  
  79.                 </div>  
  80.                 <div class="col-md-6">  
  81.                     <div class="form-group">  
  82.                         <label asp-for="ConfirmPassword" class="lable-control"></label>  
  83.                         <input asp-for="ConfirmPassword" class="form-control" />  
  84.                         <span asp-validation-for="ConfirmPassword" class="text-danger"></span>  
  85.                     </div>  
  86.                 </div>  
  87.             </div>  
  88.             <div class="form-group">  
  89.                 <button type="submit" class="btn btn-primary rounded-0">Submit</button>  
  90.             </div>  
  91.         </form>  
  92.     </div>  
  93. </div>  
Step 5 
 
Build and run your application by pressing ctrl+F5
 
Model Validation In ASP.NET MVC Core 3.1