选中复选框后动态更改jQuery Validate规则 [英] Dynamically changing a jQuery Validate rule when a checkbox is checked

查看:89
本文介绍了选中复选框后动态更改jQuery Validate规则的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用jQuery Validation来验证表单,我想做的是...我希望对其进行设置,例如,如果选中了复选框,而不是对editbox进行了不同的验证.

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 }

这是检查它的方式.

weight: { required: true, max: 100 }

有什么想法吗?

推荐答案

您将使用验证插件的内置 rules('add')方法,以便在每次选中复选框时动态更改规则.

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>

工作示例: http://jsfiddle.net/3hGxS/

Working Demo: http://jsfiddle.net/3hGxS/

这篇关于选中复选框后动态更改jQuery Validate规则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆