Custom Model Validation In ASP.NET Core 3.1

This article explain how to create custom model validation in ASP.net core. We have model validation in System.ComponentModel.DataAnnotations namespace. Validation attributes let you specify validation rules for model properties. We can create custom validation attributes, create a class that inherits from ValidationAttribute, and override the IsValid method. Here is the code.
 
The IsValid method accepts an object named value, which is the input to be validated. An overload also accepts a ValidationContext object, which provides additional information, such as the model instance created by model binding.
 

ValidationAttribute class

 
This class is the base class for all validation attributes in System.ComponentModel.DataAnnotations namespace.
 
Methods
Description
GetValidationResult(Object, ValidationContext)
This checks whether the specified value is valid with respect to the current validation attribute.
IsDefaultAttribute()
When overridden in a derived class, indicates whether the value of this instance is the default value for the derived class. Inherited from Attribute.
IsValid(Object)
Determines whether the specified value of the object is valid.
IsValid(Object, ValidationContext)
This validates the specified value with respect to the current validation attribute.
MemberwiseClone()
This creates a shallow copy of the current Object. It is Inherited from Object
ToString()
This returns a string that represents the current object. It is Inherited from Object
Validate(Object, String)
This validates the specified object.
Validate(Object, ValidationContext)
This validates the specified object.
 
Step 1
 
Start-up Visual Studio 2019. Now click on create new project and Choose ASP.NET Core Web Application and click on “Next”.
 
Custom Model Validation In ASP.NET 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.
 
Custom Model Validation In ASP.NET Core 3.1
 
That will open up another new wizard. Select ASP.Net Core 3.1 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.
 
Custom Model Validation In ASP.NET Core 3.1
 
Step 2
 
Now right click on Models folder and “Add” class and name it Student.
  1. using MvcCoreCustomModelValidation_Demo.CustomValidation;  
  2. using System;  
  3. using System.ComponentModel.DataAnnotations;  
  4.   
  5. namespace MvcCoreCustomModelValidation_Demo.Models  
  6. {  
  7.     public class Student  
  8.     {  
  9.         [Key]  
  10.         public int Id { getset; }  
  11.   
  12.         [Required(ErrorMessage = "Please enter name")]  
  13.         public string Name { getset; }  
  14.   
  15.         [Required(ErrorMessage = "Please choose admission date.")]  
  16.         [Display(Name = "Admission Date")]  
  17.         [DataType(DataType.Date)]  
  18.         [CustomAdmissionDate(ErrorMessage = "Admission Date must be less than or equal to Today's Date.")]  
  19.         public DateTime AdmissionDate { getset; }  
  20.   
  21.         [Display(Name = "Date of Birth")]  
  22.         [DataType(DataType.Date)]  
  23.         [Min18Years]  
  24.         public DateTime DateofBirth { getset; }  
  25.     }  
  26. }  
Step 3
 
Right click on project and “Add” folder CustomValidation. Now “Add” two classes, CustomAdmissionDate and Min18Years, respectively. Inherit from ValidationAttribute class override method IsValid with bool property.
  1. using System;  
  2. using System.ComponentModel.DataAnnotations;  
  3.   
  4. namespace MvcCoreCustomModelValidation_Demo.CustomValidation  
  5. {  
  6.     public class CustomAdmissionDate : ValidationAttribute  
  7.     {  
  8.         public override bool IsValid(object value)  
  9.         {  
  10.             DateTime dateTime = Convert.ToDateTime(value);  
  11.             return dateTime <= DateTime.Now;  
  12.         }  
  13.     }  
  14. }  
  1. using MvcCoreCustomModelValidation_Demo.Models;  
  2. using System;  
  3. using System.ComponentModel.DataAnnotations;  
  4.   
  5. namespace MvcCoreCustomModelValidation_Demo.CustomValidation  
  6. {  
  7.     public class Min18Years : ValidationAttribute  
  8.     {  
  9.         protected override ValidationResult IsValid(object value, ValidationContext validationContext)  
  10.         {  
  11.             var student = (Student)validationContext.ObjectInstance;  
  12.   
  13.             if (student.DateofBirth == null)  
  14.                 return new ValidationResult("Date of Birth is required.");  
  15.   
  16.             var age = DateTime.Today.Year - student.DateofBirth.Year;  
  17.   
  18.             return (age >= 18)  
  19.                 ? ValidationResult.Success  
  20.                 : new ValidationResult("Student should be at least 18 years old.");  
  21.         }  
  22.     }  
  23. }  
Step 4
 
Now open HomeController which is added when we created the new project. Write the following code for New IActionResult methods.
  1. using Microsoft.AspNetCore.Mvc;  
  2. using MvcCoreCustomModelValidation_Demo.Models;  
  3.   
  4. namespace MvcCoreCustomModelValidation_Demo.Controllers  
  5. {  
  6.     public class HomeController : Controller  
  7.     {  
  8.         public IActionResult Index()  
  9.         {  
  10.             return View();  
  11.         }  
  12.   
  13.         public IActionResult New()  
  14.         {  
  15.             return View();  
  16.         }  
  17.   
  18.         [HttpPost]  
  19.         [ValidateAntiForgeryToken]  
  20.         public IActionResult New(Student student)  
  21.         {  
  22.             if (ModelState.IsValid)  
  23.             {  
  24.                 RedirectToAction("Index");  
  25.             }  
  26.             return View();  
  27.         }  
  28.     }  
  29. }  
Step 5
 
Right click on New IActionResult method. “Add” view with default name “New”. Write the following code.
  1. @model MvcCoreCustomModelValidation_Demo.Models.Student  
  2.   
  3. @{  
  4.     ViewData["Title"] = "New";  
  5. }  
  6.   
  7. <div class="card">  
  8.     <div class="card-header">  
  9.         <h4 class="text-uppercase">Student Information</h4>  
  10.     </div>  
  11.     <div class="card-body">  
  12.         <form asp-action="New">  
  13.             <div class="form-group">  
  14.                 <label asp-for="Name" class="label-control"></label>  
  15.                 <input asp-for="Name" class="form-control" />  
  16.                 <span asp-validation-for="Name" class="text-danger"></span>  
  17.             </div>  
  18.             <div class="row">  
  19.                 <div class="col-md-6">  
  20.                     <div class="form-group">  
  21.                         <label asp-for="AdmissionDate" class="label-control"></label>  
  22.                         <input asp-for="AdmissionDate" class="form-control" />  
  23.                         <span asp-validation-for="AdmissionDate" class="text-danger"></span>  
  24.                     </div>  
  25.                 </div>  
  26.                 <div class="col-md-6">  
  27.                     <div class="form-group">  
  28.                         <label asp-for="DateofBirth" class="label-control"></label>  
  29.                         <input asp-for="DateofBirth" class="form-control" />  
  30.                         <span asp-validation-for="DateofBirth" class="text-danger"></span>  
  31.                     </div>  
  32.                 </div>  
  33.             </div>  
  34.             <div class="form-group">  
  35.                 <button type="submit" class="btn btn-sm btn-primary rounded-0">Submit</button>  
  36.             </div>  
  37.         </form>  
  38.     </div>  
  39. </div>  
Step 6
 
Built and run the application; ctrl+F5.
 
Custom Model Validation In ASP.NET Core 3.1 
Custom Model Validation In ASP.NET Core 3.1