Dynamically change jQuery validation rule when checked

I use jQuery validation to validate the form, and what I would like to do is ... I want it to be configured so that the checkbox is checked, for example, the edit box is checked differently.

Here's how it should be checked if the box is not checked:

weight: { required: true, max: 50 }

Here's how it should be checked if it is checked.

weight: { required: true, max: 100 }

Any ideas?

+5
source share
2 answers

You use the Validated plugin built-in methodrules('add') to dynamically change a rule whenever a checkbox is selected on it.

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/

+7
source

, max . , .. ().

rules: {
    field1:
    {
        required: true,
        max: function () { return $("#mycheckbox:checked").length ? 100 : 50; }
    }
}

, , , ,

$('#mycheckbox').on('change', function () {
    $('#field1.error').each(function () {
        $(this).valid();
    });
});

, , , errorClass .

html,

<input name="mycheckbox" id="mycheckbox" type="checkbox" />
<input name="field1" id="field1">
<input type="submit" />

JavaScript ,

$(function () {

   $("form").validate({
        rules: {
          field1:
          {
            required: true,
            max: function () {
                    return $("#mycheckbox:checked").length ? 100 : 50;
                }
            }
         },
        submitHandler: function () {
            alert('form ok');
        }
    });

    $('#mycheckbox').on('change', function () {
        $('#field1.error').each(function () {
            $(this).valid();
        });
    });

});
+3

All Articles