How To Perform Custom Validation Using Validation Attribute In ASP.NET MVC

Let us see how to do it.

Step 1

First of all create ASP.NET MVC app with the name MyApp.

Step 2

Add folder with the name Validator in your Application.

Step 3

Inside the folder, add class with the name FirstNameValidator.

Now, derive this FirstNameValidator class from ValidationAttribute class and execute the code given below in order to perform validation on FirstName model field.

  1. //add this namespace  
  2. using System.ComponentModel.DataAnnotations;  
  3. namespace MyApp.Models {  
  4.     public class FirstNameValidator: ValidationAttribute {  
  5.         protected override ValidationResult IsValid(object value, ValidationContext validationContext) {  
  6.             if (value != String.Empty) {  
  7.                 return ValidationResult.Success;  
  8.             } else {  
  9.                 return new ValidationResult(“First Name is required!!!“);  
  10.             }  
  11.         }  
  12.     }  
  13. }  
Step 4

Now, in your model, add this FirstNameValidator attribute to model field in order to fire validation against the model field.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.ComponentModel.DataAnnotations;  
  6. //add below line   
  7. using MyApp.Validator;  
  8. namespace MyApp.Models {  
  9.     public class SandipPatilsModel {  
  10.         [FirstNameValidator]  
  11.         public string FirstName {  
  12.             get;  
  13.             set;  
  14.         }  
  15.         public string Email {  
  16.             get;  
  17.             set;  
  18.         }  
  19.     }  
  20. }  
Summary

When the user submits the data without entering information in First Name field, it is going to fire and First Name is required.