Custom function in jquery validation engine with arguments

I want to write a new validation rule for the JQuery Validation Engine . It seems that all you need to do is write a function like this:

"myNewRule": "func": function(field, rules, i, options){ //new validation function }, "alertText": "message to be displayed if something goes wrong" }, 

Now, does anyone know how I can access the field identifier (or name) or how to pass arguments? I need to check that field B has a value not less than field A, so it is very important to know which field should be compared with ...

+4
source share
1 answer

Ok, I figured it out.

  • The first argument (for example, a field) is a field object, so you can call jQuery methods on it, for example. you use field.val() to get the field value.
  • The second argument is an array containing all the rules that you have selected for this field, they are separated by a comma, and this array excludes the brackets [] and commas.
  • i+1 gives you a position in the rules array where your rule begins, and can be very useful if you have arguments.
  • The last argument contains all the information about the validation rules in your form, but you really don't need it.

I needed to verify that the field is more important than the other, so I did the following:

JavaScript:

 function geThan(field, rules, i, options){ var a=rules[i+2]; if(parseFloat(field.val()) < parseFloat( jQuery("#"+a).val() ) ){ return "Value is smaller than a, and should be greater than or equal to it." } } 

and html:

  <input type="text" id="porce_1" name="porce_1" data-validation-engine="validate[required,custom[number],min[0],max[100]]"> <input type="text" id="porce_2" name="porce_2" data-validation-engine="validate[required,custom[number],min[0],max[100],funcCall[geThan[porce_1]]]"> 

I did not place my code inside the plugin, as I originally thought, but in the chapter section of my page and instead used funcCall .

+10
source

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


All Articles