如何使用jquery验证插件动态添加验证规则

时间:2015-11-06 11:46:15

标签: javascript jquery validation jquery-plugins

我正在尝试使用http://jqueryvalidation.org/动态地将验证规则添加到某些动态控件中,但它无效。

 $(".rtxt").each(function () {
             $(this).rules('add', {
                 required: true
             });
         });

 <input class='rtxt'  name='txtDocName' id='txtDocName' style='width:220px;' type='text' >

不知道我在这里失踪了什么。

我不能使用'required'属性,因为它不支持IE9所以我将不得不使用jquery验证插件。

这是小提琴

http://jsfiddle.net/ed4fg1xo/

另外,我需要对div click事件进行验证。

1 个答案:

答案 0 :(得分:0)

$(document).ready(function () {
    // 1. prepare the validation rules and messages.
    var rules = {
        textbox1: {
            required: true,
            minlength: 2
        },
        textbox2: "required",
        textbox3: "required"
    };
    var messages = {
        textbox1: {
            required: "textbox1 is required",
            minlength: "textbox1 needs to be at least length 2"
        },
        textbox2: "textbox2 is requried",
        textbox3: "textbox3 is required"
    };

    // 2. Initiate the validator
    var validator
        = new jQueryValidatorWrapper("FormToValidate",
            rules, messages);

    // 3. Set the click event to do the validation
    $("#DivIdName").click(function () {
        if (!validator.validate())
            return;

        alert("Validation Success!");
    });
});