custom validation in mvc using data annotations

If you are developing web application, data validation is one of the major aspect while developing applications. ASP.Net MVC has defined a great approach for data validation using Data Annotations. One may have query that how can we implement our own custom validation which should act like data annotations. So here I am going to narrate how we can create custom validation in MVC using data annotations.

In order to achieve this, we will first create a sample application in MVC and then we will implement it step by step.

First of all, create new MVC project in visual studio by clicking on File -> New -> Project.

Once you create new project, you will see in Solution Explorer that there are three folders named Models, Views and Controllers. Right click on Models folder and create new class and give it a nice name EmployeeModel.cs. Once you create class, add properties (FirstName, LastName, EmployeeId) into it as shown below:

As you can see in above properties, we have already applied required validations to FirstName and LastName. Now as per the requirement I want to add validation in EmployeeId which should fall in below criteria:

  • ID should always start with ’emp’
  • ’emp’ should followed by numbers. For example, emp0001
  • Length of EmployeeId should not exceed 10 characters.

As we all know that MVC does not provide any default validation for this. So here custom validation comes into picture and we need to create our custom validation which can validate EmployeeId as per requirement mentioned above.

So for this, the first step is to create a new class named EmployeeIdValidator.cs and inherit ValidationAttribute class. Once we create it, override two methods of ValidationAttribute class and apply custom logic to validate EmployeeId as mentioned below:

Now we are ready to use our custom validation in EmployeeId. Just add attribute on EmployeeId property as shown below:

That is it. You are almost done. Now you just have to include this model in your view page as shown below (I have used default Index method of HomeController  and Index.cshtml):

Now when you click on Submit button, a validation message will be displayed if EmployeeID is not in valid format. Cheers