【问题标题】:is there any way to remove the default error from input type email when user enter the incorrect email address?当用户输入错误的电子邮件地址时,有没有办法从输入类型的电子邮件中删除默认错误?
【发布时间】:2022-09-23 15:47:09
【问题描述】:

当用户输入错误的电子邮件地址时,有没有办法从输入类型的电子邮件中删除默认错误?因为我正在使用电子邮件地址进行表单验证。我可以从输入电子邮件中看到默认错误,但在我的控制台上看不到。

<div class=\"registration-box\">
        <form id=\"form-data\">
          <input
            type=\"email\"
            placeholder=\"Email Address\"
            class=\"email-id\"
            id=\"email-data\"
          />

          <span class=\"btn-box\"
            ><input type=\"submit\" class=\"submit\" value=\"submit\" /></span>
        </form>
      </div>
      <div class=\"error-msg\">Please provide a valid email</div>
const formData = document.getElementById(\"form-data\");
const emailAdd = document.querySelector(\"input[type=\'email\']\");
const emailReg = /^[(\\w\\d\\W)+]+@[\\w+]+\\.[\\w+]+$/i;

formData.addEventListener(\"submit\", (e) => {
  e.preventDefault();

  if (emailReg.test(emailAdd.value)) {
    console.log(\"correct\");
  } else {
    console.log(\"error\");
  }
});
  • 如果您不想要内置验证,请不要使用type=email

标签: javascript


【解决方案1】:

您可以通过禁用表单身份验证来完成此操作,当您执行此操作时,您需要确保您的身份验证是防水的。

我们都知道默认情况下股票验证有多难看,您可以通过将novalidate 添加到您的&lt;form&gt; 来禁用此功能

这是一个验证示例,如果email.checkValidity() 返回false,则向用户显示自定义错误消息

let email = document.getElementsByClassName("user-input__form-email")[0];

function validate_email() {
  if (!email.checkValidity()) {
    document.getElementById("error").innerHTML = "E-mail is not correct";
    return false;
  } else {
    document.getElementById("error").innerHTML = "";
    return true;
  }
}
console.log("email " + email.value + "  " + email.checkValidity());
<form onsubmit="return validate_email(this)" novalidate>
  <input type="email" placeholder="Email Address" class="user-input__form-email" required>
  <p id="error" style="color: red;"></p>
  <input type="submit" onsubmit="return validate_email(this)">
</form>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-10-02
    • 2010-12-04
    • 1970-01-01
    • 2021-01-18
    • 1970-01-01
    • 2010-09-05
    • 2016-02-05
    相关资源
    最近更新 更多