5

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...

1 Answer 1

12

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.