MVC : Custom validation attribute with Data Annotation

How to create custom validation attribute in ASP.NET MVC

Data annotation attributes are heavily used in MVC data validations when posting or entering the data into the forms. MVC has many inbuilt data annotation attributes and we can use them for our validations. But sometimes we have to write our own validations for the form data and in that case we have to implement some custom validation attributes. This article explains how to create a custom validation attribute for a custom validation.

For this we can take a very practical example from the real world systems. Lets say in our system users can register by filling the registration form and they have to enter their a username. Since the username is unique, only one use account should be created with a particular username. In that case of course we can submit the form data to controller action and check the uniqueness of the username from there. but here we are going to validate the username without processing it in the controller. Simply the ModelState.IsValid will be false and we are not going to continue the processing and just show up an error to the end user.

  1. Create a new ASP.NET MVC web application project.

In default project created by the template already has the Controllers, Views and Models for the basic operations such as user registration and login.


Here we can see there are some basic validations are already implemented but this is not our requirement we have to modify this to include the username field.

2. Modify the RegisterViewModel class to include the field.

In Models -> AccountViewModels class we have the RegisterViewModel class. Add a new field for username.

public class RegisterViewModel
[Display(Name = "UserName")]
public string UserName { get; set; }

[Display(Name = "Email")]
public string Email { get; set; }

[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[Display(Name = "Password")]
public string Password { get; set; }

[Display(Name = "Confirm password")]
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
3. Add the custom validation class into project.

In here I have added it inside the models folder

public class UniqueUserName : ValidationAttribute
public override bool IsValid(object value)
//implement the logic here

//  read the users from database and return false if the username already exists.

// otherwise return true.

We have inherited our custom validation attribute class from the ValidationAttribute class and overridden the IsValid method.

4. Modify the view to include the username field

Views-> Account > Register

<div class="form-group">;
@Html.LabelFor(m => m.UserName, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.TextBoxFor(m => m.UserName, new { @class = "form-control" })
5. Submit the registration form and check the functionality

custom validation attribute

If you check the controller action in debug mode you can see that the ModelState.IsValid is set to false.

debug custom validation attribute

These error messages can be configured from a resource file. So end user will see the custom user friendly message.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.