views:

339

answers:

1

I'm trying to validate a input field with the JQuery validation plugin. The numeric range [range()] depends on the value of a select box. For example when the select box is "A" the range should be between 1 and 10. But when its "B" it should be between 5 and 10 and so on. I did try this with reading out the value of of the select box and call a function to validate the input, passing the minumum value.

This works but when you select "A" and you think hmm it should be "B" it still validates as "A". I was thinking about 'depends' but I only think it works on 'required'.

$("#theSelectID").change(function () {
        var theValueOfSelected = $('#LeverancierID :selected').text();
        switch(theValueOfSelected){
        case "A":
            minval(1, "Null");
            break;
        case "B":
            minval(5, "PRCC");
            break;
            }
            function minval(theVal, theLev){
        $("#AddInkoop").validate({  
            rules: {
                Aantal: {
                    required: true,
                    range: [theVal, 999]
                }
            },
            messages: {
                Aantal:{
                    required:"required",
                    range: "give a number between "+ theVal +" and 999."
                }
            }
         });
    }
A: 

I think you are going about it backwards. Instead of changing the validation set up every time the select box changes, set up the validation rule so that it calculates the minimum value using a function that reflects the current value of the select box. Note that you may want to update some descriptive text indicating what the acceptable range is when the select changes.

 $("#AddInkoop").validate({  
        rules: {
            Aantal: {
                required: true,
                range: function() { return [ $('#LeverancierID').val(), 999 ]; }
            }
        },
        messages: {
            Aantal:{
                required:"required",
                range: "the value is outside the acceptable range"
            }
        }
});
tvanfosson
Thanks this worked, it needed a bit of modification to fit in my project, but it works.
Elvn