JQuery验证 - 确认电子邮件表单验证

Kar*_*rty -1 jquery jquery-validate

我有一个测验,我需要为一个confirm email address字段添加一些验证,基本上它只需匹配上面字段中给出的电子邮件地址.我使用以下javascript,我可以在这里添加一些东西,以确保电子邮件匹配?

if ($('#mtQuiz').length > 0) {
    $('#myQuiz').validate({
        errorElement: "em",
        errorContainer: $("#warning"),
        rules: {
            'entry[first_name]':            'required',
            'entry[last_name]':     'required',
            'entry[email]': {
                required: true,
                email: true
            },
            'entry[confirm_email]': {
                required: true,
                email: true
            }
        },
        messages: {
            'entry[first_name]':    'Please enter first name',
            'entry[last_name]': 'Please enter last name',
            'entry[email]': {
                required: ' Please enter a valid email address',
                minlength: 'Not a valid email address'
            },
            'entry[confirm_email]': {
                required: ' Please make sure email matches above',
                minlength: 'Does not match above email address'
            }
                      }
    });
}
Run Code Online (Sandbox Code Playgroud)

Spa*_*rky 8

if ($('#mtQuiz').length > 0) { // <- unnecessary and superfluous
    $('#myQuiz').validate({
        // options, etc.
    });
}
Run Code Online (Sandbox Code Playgroud)

您正在使用jQuery,所以你并不需要检查是否存在#myQuizif ($('#mtQuiz').length > 0).如果#myQuiz元素不存在,jQuery将简单地忽略它而没有任何错误.

这就是你需要做的一切......

$('#myQuiz').validate({  // initialize the plugin
    // options, etc.
});
Run Code Online (Sandbox Code Playgroud)

要匹配其他字段的值,只需使用equalTo规则即可.使用equalTo规则时,不需要复制任何其他规则,因为equalTo它将始终强制该值与已遵循其规则的主要字段的值匹配.

$('#myQuiz').validate({
    // options, etc.,
    rules: {
        'entry[first_name]': 'required',
        'entry[last_name]': 'required',
        'entry[email]': {
            required: true,
            email: true
        },
        'entry[confirm_email]': {
            //required: true,  // <- redundant, not needed with 'equalTo'
            //email: true      // <- redundant, not needed with 'equalTo'
            equalTo: '[name="entry[email]"]' // <- any valid jQuery selector
        }
    },
    // other options, etc.
});
Run Code Online (Sandbox Code Playgroud)

演示:http: //jsfiddle.net/JCY2E/