Sunday, May 31, 2009

[jQuery] variable validation rules for the same input field depending on other fields

I have the following html, field xxx requires a number from 0 to 100
when percentage is selected, and 0 to inifinity when dollar is
selected. what's the best practice to setup validation for this? the
key is to control the maximum value. I have tried depends expression
in a max rule, but it doesn't seem that it can satisfy my requirement.
form.validate({
xxx:{
number:true,
max:{
depends:function(el){
var unit = $('#xxx_unit').val();
if(unit=='percentage'){
return 100;
}
return MAX_DOLLAR_AMOUNT;
},

},
min:0
}
});

<input id="xxx" name="xx" type="text" maxlength="10" value=""/
>

<select id="xxx_unit" name="xxx_unit">
<option value="percent">Percentage</option>
<option value="dollar">Dollar Amount</option>
</select>

No comments: