Search code examples
jqueryvalidationjquery-validation-engine

custom function in JQuery validation engine with arguments


I want to write a new validation rule for JQuery Validation Engine. It seems all you have to do is to 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 can I access the field id (or name) or how can I pass arguments? I need to verify that field B has a value no less than field A, so it's really important to know what field should I compare to...


Solution

  • Okay, I figured it out.

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

    I needed to verify that a field had a greater value than another, 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 the html is:

        <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 didn't place my code inside the plugin, as I had initially thought, but in the head section of my page and used funcCall instead.