Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery validation - changing value of max at runtime

I have these validation rules:

$("#ed_details").validate({
    rules: {
        tagno: { required: true },
        itemid: { required: true },
        ralno: { required: true },
        feet: { required: true, number: true, min: 0 },
        inches: { required: true, number: true, min: 0 },
        cms: { required: true, number: true, min: 0 },
        length: { required: true, number: true, max: $('#maxlength').val() },
        qty: { required: true }
    }
});

This is the field that lengths validates against. It is text only for testing purposes. It will be hidden once this is working.

<input type="text" name="maxlength" id="maxlength" value="<?=$maxL['ml']?>" />

This works fine unless I change the value of maxlength at runtime (which can happen). The user is selecting an item from a drop down. Each item has a maximum length of tubing that can be used with it. When the item changes, the value of maxlength does change on the screen. However, when the validation runs, I see an error message based on the original length (0 for a new item, whatever the maxlength was at load for an edit).

Please enter a value less than or equal to 156.

I see this even when the maxlength field shows another value.

If I use Firebug on the field, it shows the original value even after it has been changed. Also, changing the maxlength field by hand instead of code does not make a difference.

Any help is greatly appreciated.

like image 841
Frank Luke Avatar asked Jan 22 '13 21:01

Frank Luke


2 Answers

You can not change rules like this...

length: { 
    required: true,
    number: true, 
    max: $('#maxlength').val()
},

That's because, like most jQuery plugins, .validate() is called only one time to initialize the plugin on your form... it does not run repeatedly, so dynamically changing the rules options within .validate() does nothing.

Use the rules method to add and update your rules dynamically. (use along with the code that changes the value.)

$('#maxlength').rules("add", {
     max: $('#maxlength').val()
});

See this very crude "proof of concept" demo below (room for you to rearrange). Test the form (value is initially 5). Then click the button one time and the value and rule (along with message) are updated correctly to "2".

http://jsfiddle.net/Y565M/

http://docs.jquery.com/Plugins/Validation/rules#.22add.22rules

like image 78
Sparky Avatar answered Oct 13 '22 07:10

Sparky


You can do like this too :

function ()  { return $("#maxlength").val()  }

In this case :

length : {  required:  true, number: true, max: function () { return $("#maxlength").val()  }  }
like image 29
julio Avatar answered Oct 13 '22 07:10

julio