In MVC as you are aware validation can be applied at the model level, similarly that can be done in ASP.NET Core.
ASP.NET Core Built-in Model Validation Attributes
The following are some of the common built-in validation attributes in ASP.NET Core
Attribute | Purpose |
---|---|
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 |
In controller action method to check if valiation is succesfull, we will use ModelState.IsValid Property.
Displaying Model Validation Errors
To display validation errors use asp-validation-for and asp-validation-summary tag helpers.
To display the validation error associated with the Name property use asp-validation-for tag helper on a <span> element as shown below.
<div class="form-group row">
<label asp-for="Name" class="col-form-label"></label>
<div>
<input asp-for="Name" class="form-control" placeholder="Name">
<span asp-validation-for="Name"></span>
</div>
</div>
To display a summary of all validation errors use asp-validation-summary tag helper on a <div> element as shown below.
<div asp-validation-summary="All">
</div>
The value for asp-validation-summary tag helper can be anyone from All, ModelOnly, None
Customizing Model Validation Error Message
If you want to change the default validation error message that can be done using the ErrorMessage property of the Required attribute as shown below.
Comments
Post a Comment