javascript - 使用 onkeyup 事件确保电子邮件匹配

标签 javascript function validation email onkeyup

我有这个 html 表单代码:

$("#email").blur(function(){
  //check to two here.
  if ($("#email").val() != $("#email_repeat").val())
  {
    $("#email_repeat").keyup(function(){
      if ($("#email").val() != $("#email_repeat").val()) {
        // emails don't match
      }
    });
  }
});
<label for="email">Email address:</label>
<input type="email" id="email" name="email" placeholder="em@i.l" 
       title="Enter email address" required>

<label for="email_repeat">Confirm email address:</label>
<input type="email" id="email_repeat" name="email_repeat" placeholder="em@i.l" 
       title="Confirm email address" required >

我想确保它们实时匹配,并且我知道我需要使用 on key up 事件。

我在这里错过了什么?

最佳答案

您每次检查时都在定义一个 keyup 事件。这是绝对错误和不合逻辑的。

就像你说的:

If user leaves focus on 'email' textbox and emails don't match 'email_repeat' then add an event to 'email_repeat' so if keyup occurs, if email don't match...

应该这样做:

$("#email").on('keyup', ValidateEmails); // Remove these two if you don't want it to be
$("#email_repeat").on('keyup', ValidateEmails); // validated after user clicks a key

$("#email").blur(ValidateEmails); // Remove these two if you don't want it to be
$("#email_repeat").blur(ValidateEmails); // validated when a user loses focus

function ValidateEmails()
{
    if ($("#email").val() != $("#email_repeat").val())
    {
        // emails dont match
    }
}

我是这么说的:

If user leaves the focus or clicks a key on either 'email' or 'email_repeat' textboxes then check if emails are not equal

关于javascript - 使用 onkeyup 事件确保电子邮件匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30795549/

相关文章:

javascript - 如何在iOS浏览器中录制音频?

c++ - C++ 类 "helper functions"应该是成员、免费还是非命名空间免费?

r - 将参数传递给 R 中的自定义函数和过滤器

使用 @valid 进行 spring 验证 where/how 自定义错误消息

ios - Xcode 6 : "Archive validation failed with error" "Invalid image path"

javascript - 如何在 Google Analytics 中对虚拟浏览量进行分类?

javascript - jquery .click() 并不完成与实际单击链接相同的过程;需要单击实际链接才能使流程正常运行

C# 使用属性为函数计时

validation - 在 Magento 中表单验证后更改错误消息

javascript - javascript中keyup和keydown的工作有什么区别?