Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically changing a jQuery Validate rule when a checkbox is checked

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?

like image 865
William L. Avatar asked Feb 09 '13 03:02

William L.


1 Answers

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/

like image 120
Sparky Avatar answered Sep 29 '22 10:09

Sparky