简体   繁体   English

电子邮件验证始终失败

[英]Email validation is always failing

I copied most popular validation method from different StackOverflow answers, but the problem email always appears to be not valid. 我从不同的StackOverflow答案中复制了最流行的验证方法,但是问题电子邮件始终似乎无效。 So that second condition is never executed. 因此,第二个条件永远不会执行。 What am I understanding wrong? 我理解错了什么?

function validateEmail(email) {
  var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
  return re.test(email);
}
var emailaddress = document.getElementById("email_input").value;
$("#email_input").keydown(function(emailaddress) {
  if (!validateEmail(emailaddress)) {
    $('#enter_valid_email').remove()
    $('<span class="enter_smth_valid" id="enter_valid_email">Enter valid email</span>').insertAfter('#email_input')
  } else {
    alert();
    $('#enter_valid_email').remove()
  }
});

The function passed to keydown is an event handler - it receives an event object as the first parameter passed to it (if you need it). 传递给keydown的函数是一个事件处理程序-它接收一个事件对象作为传递给它的第一个参数(如果需要)。 You are treating that as the text itself. 您将其视为文本本身。 A small change will fix the problem: 进行较小的更改将解决问题:

$("#email_input").keydown(function() {
   var emailAddress = $(this).val();
  if (!validateEmail(emailAddress )) {
    $('#enter_valid_email').remove()
    $('<span class="enter_smth_valid" id="enter_valid_email">Enter valid email</span>').insertAfter('#email_input')
  } else {
    alert();
    $('#enter_valid_email').remove()
  }
});

You can also remove this line above that - it does nothing: 您还可以删除上面的这一行-它什么都不做:

var emailaddress = document.getElementById("email_input").value;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM