Custom Validation in MVC

March 25, 2018 0 Comments A+ a-

ASP .Net

Custom Validation

Validation attributes are a way to configure the model. Some validation rules are implemented based on your business. Your business rules might not be data data annotations validation. You need to implement for new business rule in your MVC application. This case you can go to custom validation.
Please follow the below steps to create your own custom validation in MVC application.
  • Create a class inheriting ValidationAttribute.
  • Override IsValid method and write your custom validation logic there.
  • Add class name as validation attribute on the model property.
Let's the below Code snippet for creating Custom Validation. AgeValidate.cs
   
  public class AgeValidate: ValidationAttribute
    {
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {  
            if (value == null)
            {
                return new ValidationResult("Please enter Date of Birth.");
            }
            else
            {
                DateTime DOB = Convert.ToDateTime(value);
                int age = (Int32.Parse(DateTime.Now.ToString("yyyyMMdd")) -
                       Int32.Parse(DOB.ToString("yyyyMMdd"))) / 10000;
                return age < 18 ? new ValidationResult("Age of employee must be greater then 18 years.")
                    : ValidationResult.Success;
            }
        }
    }
EmployeeController.cs
   
  public class EmployeeController : Controller
    {
        // GET: Employee
        public ActionResult Index()
        {
            return View();
        }
        [HttpGet]
        public ActionResult Registration()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Registration(Employee emp)
        {
            if(!ModelState.IsValid)
            {
                return View("Registration", emp);
            }
            return View();
        }
    }
Registration.cshtml
   
@model DataAnnotationTest.Models.Employee
@{
    ViewBag.Title = "Registration";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

Registration

@using (Html.BeginForm()) {

@Html.ValidationSummary(true, "", new { @class = "text-danger" })
@Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
@Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
@Html.LabelFor(model => model.DOB, htmlAttributes: new { @class = "control-label col-md-2" })
@Html.EditorFor(model => model.DOB, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.DOB, "", new { @class = "text-danger" })
}
@Html.ActionLink("Back to List", "Index")
Now run the application and see the below output.
Custom Validation in MVC
Fig -1
Custom Validation in MVC
Fig - 2
Custom Validation in MVC
Fig - 3

Figure 1,2 and 3 are the output of our application.