1

是否有可能通过通配符添加规则?我认为不可能制定这样的规则......

$("#form").validate({
        // errorLabelContainer: $("div#error"),
        errorElement: "p",
        errorClass: "form-error",
        rules: {
             $("input[name*='x.child']"): {
                required: true,
                minlength: 5
            }
        }
});
4

1 回答 1

8

使用内置rules()方法添加规则。 请参阅文档。

注意:调用必须调用该方法。.validate()

jsFiddle 演示

$("#form").validate({
    errorElement: "p",
    errorClass: "form-error"
});

// the following method must come AFTER .validate()
$("input[name*='x.child']").each(function() {
    $(this).rules('add', {
        required: true,
        minlength: 5
    });
});

当您向表单动态添加字段时,此方法也非常有用。

以下与 custom 结合使用messages:。请注意,格式与将规则添加为选项时略有不同.validate()...

$("input[name*='x.child']").each(function() {
    $(this).rules('add', {
        required: true,
        minlength: 5,
        messages: {
            required: "Required input",
            minlength: jQuery.format("At least {0} characters are necessary")
        }
    });
});

如其他地方所述,您还可以像这样创建class和使用...

jsFiddle 演示

HTML:

<input type="text" class="myclass" name="whatever" />

jQuery:

$("#form").validate({
    errorElement: "p",
    errorClass: "form-error"
});

// the following method must come AFTER .validate()
$('#form').find('.myclass').each(function() {
    $(this).rules('add', {
        required: true,
        minlength: 5,
        messages: {
            required: "Required input",
            minlength: jQuery.format("At least {0} characters are necessary")
        }
    });
});
于 2012-12-14T22:33:45.873 回答