ASP.NET Core built-in model validation attributes
ASP.NET Core provides several built-in attributes for model validation. The following is the complete list.
- Required - Specifies the field is required
- Range - Specifies the minimum and maximum value allowed
- MinLength - Specifies the minimum length of a string
- MaxLength - Specifies the maximum length of a string
- Compare - Compares 2 properties of a model. For example compare Email and ConfirmEmail properties
- RegularExpression - Validates if the provided value matches the pattern specified by the regular expression
These validation attributes are in System.ComponentModel.DataAnnotations namespace. Also do not forget to install the following Nuget package.
Model Validation in ASP.NET Core REST API
To implement model validation in an ASP.NET Core REST API, decorate the respective properties with the validation attributes. In the following example, FirstName is a required property. Should contain a minimum of 2 characters and must not exceed 100 characters.
Custom model validation errors in ASP.NET Core REST API
To add a custom model validation error, use AddModelError() method of the ModelState object.
ASP.NET Core REST API and ModelState.IsValid check
In an ASP.NET Core REST API, there is no need to explicitly check if the model state is Valid. Since the controller class is decorated with the [ApiController] attribute, it takes care of checking if the model state is valid and automatically returns 400 response along the validation errors.
The following is the response we get when the model validation fails
No comments:
Post a Comment