JQuery validation - changing max value 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 for which the length is checked. This text is for testing purposes only. It will be hidden after it works.

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

This works fine if I don't change the maxlength value at runtime (which could happen). The user selects an item from the drop-down list. Each item has a maximum tube length that can be used with it. When an element changes, the value of maxlength changes on the screen. However, when checking is done, I see an error message based on the original length (0 for the new item, no matter what the maximum length was when loading for editing).

Please enter a value less than or equal to 156.

I see this even if the maxlength field shows a different value.

Firebug , . , maxlength .

.

+5
4

rules ...

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

, , jQuery, .validate() one form... , rules .validate() .

rules add . ( , .)

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

" " ( , ). ( 5). , ( ) "2".

http://jsfiddle.net/Y565M/

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

+6

:

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

:

length : {  required:  true, number: true, max: function () { return $("#maxlength").val()  }  }
+2

perhaps you can add an intrinsically safe method to changetrigger

$('#maxlength').change(function() {
    $('#ed_details').rules('remove', 'length');
    $('#ed_details').rules('add', { length : { required: true, number: true, max: $('#maxlength').val() } });
});
0
source

You can create a custom validator that passes to the input selector, which would provide the maximum value:

$.validator.addMethod("MaxFromValue", function (val, ele, arg) {
    var max = $(arg).val();
    return this.optional(ele) || !(val > max);
}, $.format("Value cannot be greater than '{0}'"));
  • this is untested code ... use with caution *
0
source

All Articles