Create a Custom Validation Attribute

Photo by Scott Graham on Unsplash

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.

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.

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.

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.

Software Engineer at Kainos. Normally found on a golf course or watching football. All views expressed here are my own.