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.
Step 3
Select the "empty" template, check on the MVC, and click OK.
Step 4
Right-click on Models folder, choose “Add”, then choose the class. Name it as Employee.cs.
After clicking on class, another window pops up. Select class, name it as Employee, and click on “Add”.
Employee Class
- using System;
- using System.Collections.Generic;
- using System.ComponentModel.DataAnnotations;
- using System.Linq;
- using System.Web;
- using MvcCustomValidationAttribute_Demo.CustomValidation;
-
- namespace MvcCustomValidationAttribute_Demo.Models
- {
- public class Employee
- {
- public int Id { get; set; }
-
- [Required(ErrorMessage = "Please enter name")]
- public string Name { get; set; }
-
- [Required(ErrorMessage = "Please enter position")]
- public string Position { get; set; }
-
- [Required(ErrorMessage = "Please enter office")]
- public string Office { get; set; }
-
- [Required(ErrorMessage = "Please enter hire date")]
- [Display(Name = "Hire Date")]
- [DisplayFormat(DataFormatString = "{0:d}",ApplyFormatInEditMode = true)]
- [CustomHireDate(ErrorMessage = "Hire Date must be less than or equal to Today's Date")]
- public DateTime HireDate { get; set; }
-
- [Required(ErrorMessage = "Please enter salary")]
- public int Salary { get; set; }
- }
- }
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
- using System;
- using System.Collections.Generic;
- using System.ComponentModel.DataAnnotations;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
-
- namespace MvcCustomValidationAttribute_Demo.CustomValidation
- {
- public class CustomHireDate:ValidationAttribute
- {
- public override bool IsValid(object value)
- {
- DateTime dateTime = Convert.ToDateTime(value);
- return dateTime <= DateTime.Now;
- }
- }
- }
Step 6
Right-click on the Controllers folder and add a new controller.
A window will appear. Choose MVC5 Controller-Empty and click "Add".
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.
Home Controller Code
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
- using MvcCustomValidationAttribute_Demo.Models;
-
- namespace MvcCustomValidationAttribute_Demo.Controllers
- {
- public class HomeController : Controller
- {
-
- public ActionResult Index()
- {
- return View();
- }
-
- [HttpGet]
- public ActionResult Create()
- {
- return View();
- }
-
- [HttpPost]
- [ValidateAntiForgeryToken]
- public ActionResult Create(Employee employee)
- {
- if (ModelState.IsValid)
- {
- RedirectToAction("Index");
- }
-
- return View();
- }
- }
- }
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
- @model MvcCustomValidationAttribute_Demo.Models.Employee
-
- @{
- ViewBag.Title = "Create";
- }
-
- @using (Html.BeginForm())
- {
- @Html.AntiForgeryToken()
-
- <div class="form-horizontal">
- <h4>Create Employee</h4>
- <hr />
- @Html.ValidationSummary(true, "", new { @class = "text-danger" })
- <div class="form-group">
- @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
- <div class="col-md-10">
- @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
- @Html.ValidationMessageFor(model => model.Name)
- </div>
- </div>
-
- <div class="form-group">
- @Html.LabelFor(model => model.Position, htmlAttributes: new { @class = "control-label col-md-2" })
- <div class="col-md-10">
- @Html.EditorFor(model => model.Position, new { htmlAttributes = new { @class = "form-control" } })
- @Html.ValidationMessageFor(model => model.Position)
- </div>
- </div>
-
- <div class="form-group">
- @Html.LabelFor(model => model.Office, htmlAttributes: new { @class = "control-label col-md-2" })
- <div class="col-md-10">
- @Html.EditorFor(model => model.Office, new { htmlAttributes = new { @class = "form-control" } })
- @Html.ValidationMessageFor(model => model.Office)
- </div>
- </div>
-
- <div class="form-group">
- @Html.LabelFor(model => model.HireDate, htmlAttributes: new { @class = "control-label col-md-2" })
- <div class="col-md-10">
- @Html.EditorFor(model => model.HireDate, new { htmlAttributes = new { @class = "form-control" } })
- @Html.ValidationMessageFor(model => model.HireDate)
- </div>
- </div>
-
- <div class="form-group">
- @Html.LabelFor(model => model.Salary, htmlAttributes: new { @class = "control-label col-md-2" })
- <div class="col-md-10">
- @Html.EditorFor(model => model.Salary, new { htmlAttributes = new { @class = "form-control" } })
- @Html.ValidationMessageFor(model => model.Salary)
- </div>
- </div>
-
- <div class="form-group">
- <div class="col-md-offset-2 col-md-10">
- <input type="submit" value="Create" class="btn btn-default" />
- </div>
- </div>
- </div>
- }
Step 8
Build and run the project by pressing ctrl+F5.