I'm using jQuery Validation to validate a form, and what I would like to do is this... I want it set so if a checkbox is checked than a editbox is validated differently, for example.
This is how it should be validate if the checkbox is not checked:
weight: { required: true, max: 50 }
This is how it should be validated if it is checked.
weight: { required: true, max: 100 }
Any ideas?
You'd use the Validate plugin's built-in rules('add')
method to dynamically change the rule whenever the checkbox is clicked.
jQuery:
$(document).ready(function () {
// initialize the plugin
$('#myform').validate({
// other options,
rules: {
// other rules,
weight: {
required: true,
max: 50 // initial value on load
}
}
});
// change the rule on checkbox and update displayed message dynamically
$('#check').on('change', function () {
if ($(this).is(':checked')) {
$('#weight').rules('add', {
max: 100
});
} else {
$('#weight').rules('add', {
max: 50
});
};
$('#weight.error').each(function () {
$(this).valid();
});
});
});
HTML:
<form id="myform">
<input type="checkbox" id="check" />
<input type="text" id="weight" name="weight" />
<input type="submit" />
</form>
Working Demo: http://jsfiddle.net/3hGxS/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With