Handling Validation in Razor Views

In this section, we will learn how to use validation-specific logic in our views.

We already used validation-specific tag helpers in some of our previous examples. Here, we explain them in detail together with the whole view validation logic.

The overall view validation framework

Views take errors set either by ASP.NET Core providers or set manually by the action method code from the ViewData.ModelState property that is filled with the same ModelStateDictionary used by the controller that rendered the view. Therefore, ViewData.ModelState contains all errors set during the action method execution, each indexed by field name.

Errors are specific to forms since they are associated with the action method triggered by a specific form submit. Thus, if a page contains several forms, our first preoccupation should be that errors are redirected to the tags of the right form.

Since there is a unique ModelStateDictionary for the whole view, this dictionary indexes all errors by field name, we must avoid giving the same name to fields that belong to different forms.

Moreover, since each form may have its validation summary, which shows errors that are not associated with any specific field, that is, errors that are all indexed by the empty string, then particular care to render only the error summary that is associated with the actual form that was submitted.

Property level errors

Input-field-level errors affect the way the input fields are rendered. More specifically, fields in error are automatically given the input-validation-error CSS class. For this to work properly, input tags must trigger the execution of tag-helpers. This happens whenever the input fields contain the asp-for attribute.

The input-validation-error CSS class can be replaced with a custom CSS class, for instance, with the Bootstrap is-invalid class with a simple jQuery snippet added to the view, as shown below:

Get hands-on with 1200+ tech skills courses.