Designing Custom Validation Attributes
Explore how to design and implement custom validation attributes in ASP.NET Core MVC. This lesson guides you through creating server-side validation logic by extending ValidationAttribute and integrating client-side validation by implementing IClientModelValidator. You will learn how to handle error messages, specify validation rules using data attributes, and connect JavaScript validation rules using jQuery unobtrusive validation adapters. By the end, you’ll be able to create modular, reusable validation attributes that enhance user input validation in web applications.
A custom validation attribute can be implemented by inheriting from the ValidationAttribute class. Server-side validation code is provided by overriding the methods that perform validation and error message formatting.
Client-side validation requires that our attribute implements the IClientModelValidator interface whose unique AddValidation method specifies the data- attributes to add to the input field. The actual client-side validation code must be provided through a JavaScript validator which is connected to the parser that processes all data- attributes through a JavaScript adapter.
We will describe all the above steps while implementing an example custom validation attribute: the ExtensionAttribute.
The ExtensionAttribute
As an example, we will define an attribute that checks the extension of a Web Address. It is useful when combined with the UrlAttribute to force the user to insert the address of a pdf, or of a supported image type. The basic idea is to pass it a string with all comma-separated allowed extensions. Something like .jpg,.jpeg, or .png. The usage should be similar to the example below:
The combined usage of both UrlAttribute and ExtensionAttribute forces the user to insert the Web Address of an image.
Server-side validation
Custom attributes can be inserted in a folder called Validation that is placed in the application root. There, we can add an ExtensionAttribute class that inherits from ValidationAttribute:
The default namespace name has been changed to match the namespace of all ViewModels, so we don’t need any
usingto use it ...