📜 ⬆️ ⬇️

The internal work of the jQuery validate unobtrusive plugin in ASP.Net MVC

This is part 3 of the series “Understanding Unobtrusive Validation in ASP.Net MVC”.

1. The jQuery validate plugin works from the inside
2. Understanding Html-code generated by unobtrusive validation in ASP.Net MVC
3. Internal work of the jQuery validate unobtrusive plugin in ASP.Net MVC.

What we will discuss in this article:

')

Method "parse"


We will explain the cycle of unobtrusive validation that occurs when the document is loaded, and understand the role of each component.
If we look at the end of jquery.validate.unobtrusive.js we will find

$(function () { $jQval.unobtrusive.parse(document); }); 

So, we call the "parse ()" method and pass it the "document"
What is the parse () method?
 { parse: function (selector) { /// <summary> /// Parses all the HTML elements in the specified selector. It looks for input elements decorated /// with the [data-val=true] attribute value and enables validation according to the data-val-* /// attribute values. /// </summary> ///Any valid jQuery selector. $(selector).find(":input[data-val=true]").each(function () { $jQval.unobtrusive.parseElement(this, true); }); var $forms = $(selector) .parents("form") .andSelf() .add($(selector).find("form")) .filter("form"); $forms.each(function () { var info = validationInfo(this); if (info) { info.attachValidation(); } }); } } 

The “parse ()” method has two sections.

1. Section "parceElement"

parseElement (element, skipAttach)

 $(selector).find(":input[data-val=true]").each(function () { $jQval.unobtrusive.parseElement(this, true); }); 

The first thing that happens is that we loop through all the elements containing “data-val = true” inside the selector that we are passing (in our case, this is “document”)
Then we call parseElement () and pass it the element that we want to validate and true for skipAttach.

Explanation of the "skipAttach" parameter

It may be asked why we pass true rather than false in skipAttach.

"SkipAttach" is a flag to call "validate ()" on a form.
If we pass “false” to the element that we pass, validation rules are attached and the “validate” method is immediately called for the array of rules, and further options are given that are necessary for unobtrusive validation (If there is any other element that they collect parsit).
We do not want this. First of all, we want to attach rules to each element of the form, and then, when all the rules are attached, we call validate (), which is the main part of the parse method.

When do we need to pass “true” to “skipAttach”?

If we want to add a dynamic element to a form that has already been validated, we will pass “true” in order not to validate the form again, because we don’t want something to happen (we will talk about dynamic validation of the element in the next article)

Explanation of the "parseElement" function

Basically, the "parseElement ()" function does two things:

1. When the form element is called for the first time (no element was called before in this form), the function constructs an object of options that will be passed to the validate () method. Options are used by jquery.unobtrusive as a separate function “errorPlacement”, a separate “errorClass” and as an empty array of rules.
Note: this can all be done in a private method “validationInfo (form)”, which is called without “parseElement”, and when it is called more than 1 time, it simply returns the same object. Thus, we can add, change or call data / functions in it.
2. For each element, when we call “parseElement”, it understands the rules that are written in this element (“the data- *”), using adapters (then there is a clause explaining how adapters work), and then translates and adds them to the array of rules that was created on the first call.
Note: Each time a parseElement is called, its result will be saved in the form using the $ .data method (“unobtrusiveValidation“). Thus, individual calls are synchronized with the same data source.

2. Section "validateInfo"

 var $forms = $(selector) .parents("form") .andSelf() .add($(selector).find("form")) .filter("form"); $forms.each(function () { var info = validationInfo(this); if (info) { info.attachValidation(); } }); 


Explanation of the "validateInfo" function

We have already mentioned that calling the function "validateInfo ()" constructs an options object of the method "validate ()". Options are used by jquery.unobtrusive as a separate function “errorPlacement”, a separate “errorClass” and an empty array of rules.
Here we also call "validateInfo ()" for each form on the page. Usually, by calling “valaidateInfo” in this place, we only get an object saved in a form that was already filled in the first phase. That is, we use it as a "getter".
Then we call “attachValidation ()”, which calls the “validate ()” method, passing it options filled with the “validationInfo ()” call.
 data_validation = "unobtrusiveValidation"; function validationInfo(form) { var $form = $(form), result = $form.data(data_validation), onResetProxy = $.proxy(onReset, form); if (!result) { result = { options: { // options structure passed to jQuery Validate's validate() method errorClass: "input-validation-error", errorElement: "span", errorPlacement: $.proxy(onError, form), invalidHandler: $.proxy(onErrors, form), messages: {}, rules: {}, success: $.proxy(onSuccess, form) }, attachValidation: function () { $form .unbind("reset." + data_validation, onResetProxy) .bind("reset." + data_validation, onResetProxy) .validate(this.options); }, validate: function () { // a validation function that is called by unobtrusive Ajax $form.validate(); return $form.valid(); } }; $form.data(data_validation, result); } return result; } 

First, we check if we have already called this function on the form earlier, using $ form.data (“unobtrusiveValidation“). If already called, then we do nothing and return the result.

Explanation of the object "return".

If this is the first call to the “validationInfo ()” function, then we create a result object and save it on the form using the $ .data () method. This object contains 3 parts:


Adapters



I specifically missed the topic of adapters when I talked about the “parseElement ()” method, because they are complex enough to highlight a sub-item for them.
We looked at how Html is generated using unobtrusive validation, and how to add individual validation attributes in normal jquery.validate. To connect these two parts are used adapters.
So, what are adapters responsible for?
Adapters are responsible for translating the Html "data- *" into a format understandable to the regular jquery.validate plugin. If a user wants to add a separate validation method using unobtrusive validation, he must also create an adapter for it. The adapter collection is located in $ .validator.unobtrusive.adapters. The adapter collection consists of all the default adapters that are defined in jquery.unobstrusive and those defined by the user.
It also contains 4 methods for adding your own adapter, which we will look at later.

Piccy.info - Free Image Hosting

The most basic method:
jQuery.validator.unobtrusive.adapters.add (adapterName, [params], fn)

We can consider this method as $ .ajax method, three other methods are auxiliary, use this method

Let's break down the parameters:

Example:
Html
 <input id="val" type="text" name="val" data-val="true" data-val-between="Must be in the right range" data-val-between-min="5" data-val-between-max="30" /> 

Javascript
 //The adapter jQuery.validator.unobtrusive.adapters.add( 'between', ['min' ,'max'], function (options) { options.rules['between'] = { min: options.params.min, max: options.params.max }; options.messages['between'] = options.message; } ); //The validation method jQuery.validator.addMethod("between", function (value, element, params) { params.min == 5; //true params.max == 30; //true }); 


What about other adapters:

addBool
addSingleVal
addMinMax

They are quite simple if you understand the concept of adding your own adapter using the add () method explained earlier.
You can also see the Brad Wilson article "Unobtrusive Client Validation in ASP.NET MVC 3" , where he explains the topic of adapters in more detail.

JQuery jade legal translation plugin works internally in Asp.net MVC

update: added a picture with a list of adapters and links to other posts in the series

Source: https://habr.com/ru/post/181758/


All Articles