多个字段的相同验证

时间:2013-08-27 06:34:01

标签: jquery validation

我有3组相同的字段,它们是3个不同成员的名字和姓氏。我正在尝试验证提交表单的字段。我附上了运行良好的验证码。

我的问题是,我的验证码现在看起来如此手动,因为我正在为每个字段编写代码。有没有办法编写单行代码来验证具有不同名称属性的相同类型的文本字段?

例如在我的ode firstname1中,firstname2,firstname3,firstname4,firstname5具有相同类型的验证,因此我想在短行中为这些字段编写验证代码,而不是写5条不同的行。

$().ready(function() {
    $("#signupForm").validate({
        rules: {
            firstname1: "required",
            firstname2: "required",
            firstname3: "required",
            lastname1: "required",
            lastname2: "required",
            lastname3: "required",

        },        
        messages: {
            firstname1: "Please enter your firstname",
            firstname2: "Please enter your firstname",
            firstname3: "Please enter your firstname",
            lastname1: "Please enter your lastname",
            lastname2: "Please enter your lastname",
            lastname3: "Please enter your lastname",

        }
    });
});

DEMO HERE

1 个答案:

答案 0 :(得分:2)

请试试这个: -

$(document).ready(function(){
    $("#signupForm").validate();
    $("input[name^=firstname]").each(function() {
        $(this).rules("add", {
            required: true,
            messages: {
            required: "Please enter your firstname"
            }
          });
    });
    $("input[name^=lastname]").each(function() {
        $(this).rules("add", {
            required: true,
            messages: {
            required: "Please enter your lastname"
            }
          });
    });
});

工作小提琴: - http://jsfiddle.net/rw9ns/34/