Reputation: 37
How to achieve the following? for the same field different range validation depending on dropdown value.
Thank You
If blue selected from dropdown then value field should be range from 200-300 if red then range from 0-100
HTML
<select name="color" id="Color">
<option value="orange" select="selected">orange</option>
<option value="blue">blue</option>
<option value="red">red</option>
<option value="yellow">yellow</option>
</select>
<input type="text" id="value" />
SCRIPT
$("#myform").validate({
rules: {
value: {
required: true,
if ($('#color').val() == "red"){
range: [0, 100]
}
if ($('#color').val() == "blue"){
range: [200, 300]
}
}
});
Upvotes: 1
Views: 4055
Reputation: 98758
Any field that you need to validate using this plugin must contain a name
attribute.
<input type="text" id="value" name="value" />
Attach an .on('change')
handler to the select
element in conjunction with the plugin's .rules()
methods.
$('#color').on('change', function() {
if ($(this).val() == "blue") {
$('#value').rules('add', {
range: [200,300]
})
} else if ($(this).val() == "red") {
$('#value').rules('add', {
range: [0,100]
})
} else {
$('#value').rules('remove');
}
});
Declare the required
rule within .validate()
to avoid interference by the .rules()
methods above.
$("#myform").validate({
rules: {
value: { // <-- this refers to the "name" attribute
required: true
}
}
});
Working DEMO: http://jsfiddle.net/3796X/
Upvotes: 3