Client-side validation

The client-side validation is really a boon to modern web applications. There were many instances that proved jQuery is helpful on both the development and the user experience front. The client-side validations were the biggest advantage we had in saving multiple round trips between client/browser to the server just to perform basic validations.

The jQuery, jQuery Validate, and jQuery Validate Unobtrusive libraries helped us in performing those basic validations on the client (browser) end rather than relying on the server in performing the same. There were multiple discussions or even arguments regarding validating the models at the client-side, which opens security considerations. The following sections will address this issue.

The task to enable client-side validation is just to provide a section for MVC to inject validation errors in the user interface, which has nothing to do with validation-related attributes (as it will be available in the model):

    <div class="form-group">
<label asp-for="Title" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="Title" class="form-control" />
<span asp-validation-for="Title" class="text-danger"></span>
</div>
</div>

The MVC templating engine will generate the HTML tags with data- attributes, which will have the same behavior for both built-in and custom validations. The rendered HTML content for the previously mentioned Title field with the Required validation is displayed as follows:

    <div class="form-group">
<label class="col-md-2 control-label" for="Title">Title</label>
<div class="col-md-10">
<input class="form-control" type="text" data-val="true" data-val-
required="Title is required"
id="Title" name="Title"
value="" />
<span class="text-danger field-validation-valid"
data-valmsg-for="Title" data-valmsg-replace="true"></span>
</div>
</div>

The validation is performed when the user tries to submit the form, which will end up in populating the error messages using client-side validation. Further, when we try to edit the messages, the Unobtrusive Validation library kicks in and does the validation way before the user submits the form again.

We have seen what client-side validation does; now, let's see what happens if the JavaScript stops working in the next section.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset