Create a Custom Validation Attribute

ASP.Net provides us with many built in validation attributes that can be added to model properties and are used to validate user input on a UI. However, there are times when the default attributes don’t fit in with your validation requirements, at this point you should be looking to write your own custom validation attribute.

Let’s look into this a bit further using a simple, easy to follow example.

Default Validation Attributes
As already mentioned, there are many default validation attributes to choose from, some of these include:

  1. [Required]: Specifies that the field is mandatory and a value must be entered
  2. [Range]: Specifies that the data entered must be within a specific range e.g. 1 to 99999
  3. [MinLength]: Validates the minimum length of the data being entered
  4. [MaxLength]: Validates the maximum length of the data being entered

The code sample below shows the above attributes on a numeric property. They include the rules required to pass validation along with the error message to be displayed if not met.

[Required(ErrorMessage = "Total cost is a mandatory field, please enter a value")]
[Range(1, 99999, ErrorMessage = "Total cost must be between 1 and 99999")]
[MinLength(1, ErrorMessage = "The total cost must be at least 1 digit")]
[MaxLength(9, ErrorMessage = "The total cost cannot exceed 5 digits")]
public decimal TotalCost { get; set; }

Custom Validation Attributes
All validation attributes including those built into ASP.NET are derived from the abstract base class ValidationAttribute. This class contains virtual methods that can be overridden, the main one being IsValid, this will be used in the example code below.

So lets look at a custom validation attribute in use. Imagine we have a web page which has an input field allowing text entry. The validation on this field is that only specific values are allowed to be entered by the user otherwise a validation error is triggered.

The model property below is decorated with a custom validation attribute that has been named ValidTextInput. The attribute provides a list of valid strings (in this case, types of house) along with the error message for when the validation rules are not met.

[ValidTextInput("Semi-Detached, Detached, Flat, Terraced", ErrorMessage = "Please enter a valid house type from the following list: Semi-Detached, Detached, Flat, Terraced")]
public string HouseType{ get; set; }

We now need the validation attribute code in which the business rules are added. The constructor of the validation attribute stores the list of valid inputs into a private variable. When the overridden method IsValid is executed, the private variable is split into a list of individual strings which the users input text is then validated against. From this a ValidationResult is returned, this will be Success if the condition is met and the ErrorMessage if validation fails.

public class ValidTextInput : ValidationAttribute
private readonly string validInputs;
public ValidTextInput(string validInputs)
this.validInputs = validInputs;
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
var validInputList = this.validInputs.Split(",");

if (!validInputList.Contains(value))
return new ValidationResult(this.ErrorMessage, new List<string>() { validationContext.MemberName });
return ValidationResult.Success;

What I’ve described is a simple example of a custom validation attribute. This pattern can be used on all data types and is not restricted to just strings. The validation can also be extended as required by adding addition business rules within the IsValid method.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store