Client-Side Validation

In this lesson, you will learn how to add and configure client-side validation that gives immediate feedback to the user.

The purpose of user input on the server-side is to protect the application from wrong inputs and malicious users. It doesn’t give immediate feedback to the user, since errors are shown only after the form has been submitted and the server returns its response.

A JavaScript-based detection of at least property-level errors improves the user experience as it immediately drives the user to correct input. ASP.NET Core MVC has built-in facilities for adding client-side validation for all its built-in validation attributes.

jquery.validate.js and unobtrusive validation

ASP.NET Core MVC client-side validation is based on the jquery.validate.js library, and on a JavaScript library that interfaces jquery.validate.js with ASP.NET Core. This overall JavaScript validation is called unobtrusive since validation rules associated with each input field are not inserted in the page as JavaScript snippets, but are defined through data- attributes added to the input tags while they are rendered.

More specifically, client-side validation rules are put in place as follows.

  1. When client-side validation is enabled, validation attributes are processed by a client-side validation adapter that adds the data- attributes that encode the client validation rules.

  2. The jquery.validate.unobtrusive.js JavaScript unobtrusive adapter launches a parser on the jQuey.ready event that is triggered as soon as the whole page HTML has been processed by the browser. This parser reads the content of all input data- validation attributes and uses them to create the encoded jquery.validate.js validation rules.

  3. Some jquery.validate.js validation rules react to the changed event that is triggered as soon as the user leaves an input field they modified, while some other rules react to the keypress event. Each time a rule failure is detected, the corresponding message error is shown in the same error placeholder used by server-side validation.

  4. When the user submits the form all rules are checked and the corresponding errors are added both to the placeholders next to the input fields, and to the same validation summary used by server-side validation. If the form contains errors the default action associated with the submit event is prevented and form data is not sent to the server.

As default client validation is enabled, we need to add just the mentioned JavaScript libraries to activate JavaScript Validation. This is easily done by adding the code below to the view:

Get hands-on with 1200+ tech skills courses.