JQuery Validate - Confirm email form validation

前提是你 提交于 2019-12-25 19:03:19

问题


I have a quiz, and i need to add some validation to a confirm email address field, basically it just has to match the email address given in the above field. I am using the following javascript, can i add something in here which will make sure the emails match?

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'
            }
                      }
    });
}

回答1:


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

You're using jQuery so you don't need to check for the existence of #myQuiz with if ($('#mtQuiz').length > 0). If the #myQuiz element doesn't exist, jQuery will simply ignore it without any errors.

This is all you need to do...

$('#myQuiz').validate({  // initialize the plugin
    // options, etc.
});

To match the value of another field, simply use the equalTo rule. While using the equalTo rule, there is no need to duplicate any of the other rules since equalTo will always force the value to match the primary field's value which already followed its rules.

$('#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.
});

DEMO: http://jsfiddle.net/JCY2E/




回答2:


Have a look to equalTo method.

$('#myQuiz').validate({
  ...
  rules: {
    ...
    'entry[confirm_email]': {
      equalTo: "entry[email]"
    }
  }
});


来源:https://stackoverflow.com/questions/22746091/jquery-validate-confirm-email-form-validation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!