首页 > 解决方案 > 我可以使用事件侦听器在使用 JavaScript 输入电子邮件地址后对其进行验证吗?

问题描述

因此,一旦用户完成将电子邮件输入到输入元素中,我将尝试验证是否输入了有效的电子邮件地址。如果他们没有输入有效的电子邮件,它会将元素边框更改为红色,如果他们确实输入了正确的电子邮件,它只会留下边框。

在不提交表格的情况下如何做到这一点?我希望它在用户键入电子邮件时或在他们取消关注元素时发生。

这是我到目前为止所拥有的,但它不起作用。

谢谢!

const emailInput = document.querySelector("#email");
const emailInputValue = emailInput.value;

emailInput.addEventListener("input", (e) => {
  if( /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/.test(emailInputValue) != true) {
      emailInput.style.border = "thin solid red"
  } else {
      emailInput.style.border = "thin solid #0000FF"
  }
})

<div id="email_div">
          <input type="email" name="email" id="email" placeholder="Email" maxlength="50">
          <label for="email" id="email_text">This field is required in order to receive an email confirmation.</label>
        </div>

标签: javascripthtmlregex

解决方案


这是输入失焦时有效的方法!

<input type="email" name="email" placeholder="Email Address" id="email_field" onChange="return emailValidation()">
<span id="email-error"></span>
<script>
function emailValidation()
{
  value = document.getElementById('email_field').value;
  apos=value.indexOf("@"); 
  dotpos=value.lastIndexOf(".");
  lastpos=value.length-1;
  if (apos < 1 || dotpos-apos < 2 || lastpos-dotpos > 3 || lastpos-dotpos < 2){
      document.getElementById("email-error").innerHTML = "Invalid Email Address";
      return false;
    } else {
      return true;
  }
}
</script> 

推荐阅读