onBlur导致Chrome中的警报消息无限循环

问题描述 投票:0回答:1

我必须制作一个HTML页面,其表单包含电子邮件地址和URL。我应该检查电子邮件是合法的Gmail还是Yahoo!格式,以及网址是否正确。但是,在Chrome上,当我输入错误的电子邮件时,如果不进行更正,则单击URL的输入,会收到无限的警报消息。

这里是HTML文件

<form action="/index.html" method="POST" name="form">
    <p>Full name:        <input type="text" pattern="[A-Z][a-z]+ [A-Z][a-z]+"></p>
    <p>Dátum:            <input type="date"></p>
    <p>Email:            <input type="email" id="email" onblur="validateEmail(document)"></p>
    <p>Kedvenc weboldal: <input type="url"   id="url"   onblur="validateFavURL(document)"></p>
</form>

以及继承人的JS文件:

function validateEmail(document) {
    let email = document.getElementById("email").value

    let regexGmail = /\S+@gmail\.\S+/
    let regexYahoo = /\S+@yahoo\.\S+/

    if (!regexGmail.test(email) || regexYahoo.test(email)) {
        alert("Incorrect email address!")
    }
}

function validateFavURL(document) {
    let url = document.getElementById("url").value

    let regexURL     = /https?:\/\/www\.[A-Za-z1-9_-]+\.[A-Za-z1-9_-]+\.[A-Za-z1-9_-]+/
    let regextwodots = /^((?!\.\.).)+/   
    let regexdots    = /\..+\./

    if (!regexURL.test(url) || !regextwodots.test(url) || regexdots.test(url)) {
        alert("Incorrect webpage!")
    }
}
javascript alert infinite-loop onblur
1个回答
0
投票

我已经更改了一些代码并添加了我的一些代码,现在警报将通过智能触发。

var hasAlreadyAlerted = false, alertedElement;
    document.querySelector("form").addEventListener('focus', (event) => 
      hasAlreadyAlerted = event.target == alertedElement, true);

    function validateEmail(emailElement) {
      let email = emailElement.value,
        regexGmail = /\S+@gmail\.\S+/,
        regexYahoo = /\S+@yahoo\.\S+/;

      if(!hasAlreadyAlerted && (!regexGmail.test(email) || regexYahoo.test(email))) {
        hasAlreadyAlerted = true;
        alertedElement = emailElement;
        alert("Incorrect email address!")
      }
    }

    function validateFavURL(urlElement) {
      let url = urlElement.value,
        regexURL = /https?:\/\/www\.[A-Za-z1-9_-]+\.[A-Za-z1-9_-]+\.[A-Za-z1-9_-]+/,
        regextwodots = /^((?!\.\.).)+/,   
        regexdots = /\..+\./;

      if (!hasAlreadyAlerted && (!regexURL.test(url) || !regextwodots.test(url) || regexdots.test(url))) {
          hasAlreadyAlerted = true;
          alertedElement = document.getElementById("url");
          alert("Incorrect webpage!")
      }
    }
<form action="/index.html" method="POST" name="form">
    <p>Full name:        <input type="text" pattern="[A-Z][a-z]+ [A-Z][a-z]+"></p>
    <p>Dátum:            <input type="date"></p>
    <p>Email:            <input type="email" id="email" onblur="validateEmail(this)"></p>
    <p>Kedvenc weboldal: <input type="url" id="url" onblur="validateFavURL(this)"></p>
  </form>
© www.soinside.com 2019 - 2024. All rights reserved.