ASP NET Core MVC model validation

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

AttributePurpose
RequiredSpecifies the field is required
RangeSpecifies the minimum and maximum value allowed
MinLengthSpecifies the minimum length of a string
MaxLengthSpecifies the maximum length of a string
CompareCompares 2 properties of a model. For example, compare Email and ConfirmEmail properties
RegularExpressionValidates 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.

public class Employee
{
    public int Id { getset; }
    [Required(ErrorMessage = "The Email field is required")]
    public string Email { getset; }
}

Comments