亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

刪除跨度標簽背景顏色

刪除跨度標簽背景顏色

不負相思意 2023-10-04 16:00:51
我有一個項目,我需要創建一個表單來驗證每個輸入,如果出現錯誤,它將顯示消息。如果沒有錯誤,則不會顯示任何消息。我已經做到了,但每次沒有錯誤時,我似乎無法刪除span標簽的紅色背景。在cleanUpErrors()我嘗試使用indicator[i].remove();但indicator[i].setAttribute("class", "hide");它們都不起作用。一旦沒有錯誤消息,就不應該有任何紅色背景。window.onload = function () {    let theForm = document.getElementById("form");    theForm.addEventListener("submit", function (event) {        let stopSubmit = false;            cleanUpErrors();            if (!checkFirstName(theForm[0])) {                theForm[0].style.borderColor = "#990000";                stopSubmit = true;            }            if (!checkLastName(theForm[1])) {                theForm[1].style.borderColor = "#990000";                stopSubmit = true;            }            if (!checkEmail(theForm[2])) {                theForm[2].style.borderColor = "#990000";                stopSubmit = true;            }            if (!checkPhone(theForm[3])) {                theForm[3].style.borderColor = "#990000";                stopSubmit = true;            }        if (stopSubmit) {            event.preventDefault();        }    }, false)}function checkFirstName(input) {    let inputValue = input.value, errorMessage = "", letters = /^[a-zA-Z]+$/, characters = /^[a-zA-Z0-9!@#\$%\^\&*\)\(+=._-]+$/g;    if (inputValue === null || inputValue === "") {        errorMessage = "This field is empty.";    }    if (inputValue !== "") {        if (inputValue.length < 3) {            errorMessage = "This field has less than 3 characters.";        }        if(!inputValue.match(letters)){            errorMessage = "Numbers detected. Please write your first name.";        }        if(!inputValue.match(characters)){            errorMessage = "Special characters detected. Please write your first name.";        }    }    renderErrorMessage(input, errorMessage);    return errorMessage === "";}
查看完整描述

2 回答

?
慕尼黑的夜晚無繁華

TA貢獻1864條經驗 獲得超6個贊

有很多代碼重復。不同字段的多個驗證函數具有共同的代碼,只是函數名稱發生變化。


相反,您可以創建一個函數數組 i:econst validationFunctions = [checkFirstName, checkLastName, checkEmail, checkPhone];


然后調用應用循環的函數。僅當滿足條件時, withspan類error才會被刪除。required


const validationFunctions = [checkFirstName, checkLastName, checkEmail, checkPhone];

validationFunctions.forEach((fun, i) => {

    if(!fun(theForm[i])) {

        theForm[i].style.borderColor = "#990000";

        stopSubmit = true;

    } else {

     document.querySelector(`#${theForm[i].id}`).nextElementSibling.style.display = "none";

   }

});

window.onload = function() {

  let theForm = document.getElementById("form");

  theForm.addEventListener("submit", function(event) {

    event.preventDefault();

    let stopSubmit = false;

    const validationFunctions = [checkFirstName, checkLastName, checkEmail, checkPhone];

    validationFunctions.forEach((fun, i) => {

      if (!fun(theForm[i])) {

        theForm[i].style.borderColor = "#990000";

        stopSubmit = true;

      } else {      document.querySelector(`#${theForm[i].id}`).nextElementSibling.style.display = "none";

      }

    });

    if (stopSubmit) {

      event.preventDefault();

    }

  }, false)

}



function checkFirstName(input) {

  let inputValue = input.value,

    errorMessage = "",

    letters = /^[a-zA-Z]+$/,

    characters = /^[a-zA-Z0-9!@#\$%\^\&*\)\(+=._-]+$/g;

  if (inputValue === null || inputValue === "") {

    errorMessage = "This field is empty.";

  }

  if (inputValue !== "") {

    if (inputValue.length < 3) {

      errorMessage = "This field has less than 3 characters.";

    }

    if (!inputValue.match(letters)) {

      errorMessage = "Numbers detected. Please write your first name.";

    }

    if (!inputValue.match(characters)) {

      errorMessage = "Special characters detected. Please write your first name.";

    }

  }

  if (input.nextElementSibling.tagName !== 'SPAN') {

    renderErrorMessage(input, errorMessage);

  }

  return errorMessage === "";

}



function checkLastName(input) {

  let inputValue = input.value,

    errorMessage = "",

    letters = /^[a-zA-Z]+$/,

    characters = /^[a-zA-Z0-9!@#\$%\^\&*\)\(+=._-]+$/g;

  if (inputValue === null || inputValue === "") {

    errorMessage = "This field is empty.";

  }

  if (inputValue !== "") {

    if (inputValue.length < 3) {

      errorMessage = "This field has less than 3 characters.";

    }

    if (!inputValue.match(letters)) {

      errorMessage = "Numbers detected. Please write your last name.";

    }

    if (!inputValue.match(characters)) {

      errorMessage = "Special characters detected. Please write your last name.";

    }

  }

  if (input.nextElementSibling.tagName !== 'SPAN') {

    renderErrorMessage(input, errorMessage);

  }

  return errorMessage === "";

}



function checkEmail(input) {

  let emailValue = input.value,

    errorMessage = "";

  let regex = /^(([^<>()\[\]\\.,;:\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,}))$/;

  if (!emailValue.match(regex)) {

    errorMessage = "Not a valid email address.";

  }

  if (emailValue === "") {

    errorMessage = "This field is empty.";

  }

  if (input.nextElementSibling.tagName !== 'SPAN') {

    renderErrorMessage(input, errorMessage);

  }

  return errorMessage === "";


}



function checkPhone(input) {

  let phoneValue = input.value,

    errorMessage = "";

  let regex = /^(((\+44\s?\d{4}|\(?0\d{4}\)?)\s?\d{3}\s?\d{3})|((\+44\s?\d{3}|\(?0\d{3}\)?)\s?\d{3}\s?\d{4})|((\+44\s?\d{2}|\(?0\d{2}\)?)\s?\d{4}\s?\d{4}))(\s?\#(\d{4}|\d{3}))?$/;

  if (!phoneValue.match(regex)) {

    errorMessage = "Not a valid UK phone number.";

  }

  if (isNaN(phoneValue)) {

    errorMessage = "No numbers detected. Please write a UK phone number.";

  }

  if (phoneValue === "") {

    errorMessage = "This field is empty.";

  }

  if (input.nextElementSibling.tagName !== 'SPAN') {

    renderErrorMessage(input, errorMessage);

  }

  return errorMessage === "";

}



function renderErrorMessage(selectedElem, errorMessage) {

  let errorElem = document.createElement("span");

  errorElem.setAttribute("class", "error");

  let errorText = document.createTextNode(errorMessage);

  errorElem.appendChild(errorText);

  selectedElem.parentNode.insertBefore(errorElem, selectedElem.nextSibling);

  return selectedElem;

}

label,

button {

  display: block;

  margin: 10px 0 5px 0;

}


input,

button {

  padding: 8px;

  width: 393px;

  font-size: 16px;

}


body,

button {

  font-family: Arial, sans-serif;

}


.error {

  color: #FFF;

  display: block;

  margin: 0 0 15px 0;

  background: #990000;

  padding: 5px 3px 5px 5px;

  width: 405px;

  line-height: 25px;

}


.hide {

  display: none;

  /* background: none; */

}

<form id="form" action="test3success.html" novalidate="novalidate">

  <label for="firstName">First Name (required)</label>

  <input id="firstName" type="text" name="text" required>


  <label for="lastName">Last Name (required)</label>

  <input id="lastName" type="text" name="text" required>


  <label for="email">Email (required)</label>

  <input id="email" type="email" required>


  <label for="phone">Phone Number (required)</label>

  <input id="phone" type="tel" required>


  <button type="submit">Submit</button>

</form>


查看完整回答
反對 回復 2023-10-04
?
子衿沉夜

TA貢獻1828條經驗 獲得超3個贊

使用一個類


通過最少的更改,我在錯誤時添加類并從所有必填字段中刪除該類


添加了代碼


theForm[X].classList.add("errorBorder")


const req = document.querySelectorAll("[required]")

for (let i=0;i<req.length;i++) {

  req[i].classList.remove("errorBorder")

}

我還會在錯誤跨度上切換類。


window.onload = function() {

  let theForm = document.getElementById("form");

  theForm.addEventListener("submit", function(event) {

    let stopSubmit = false;

    cleanUpErrors();

    if (!checkFirstName(theForm[0])) {

      theForm[0].classList.add("errorBorder")

      stopSubmit = true;

    }

    if (!checkLastName(theForm[1])) {

      theForm[1].classList.add("errorBorder")

      stopSubmit = true;

    }

    if (!checkEmail(theForm[2])) {

      theForm[2].classList.add("errorBorder")

      stopSubmit = true;

    }

    if (!checkPhone(theForm[3])) {

      theForm[3].classList.add("errorBorder")

      stopSubmit = true;

    }

    if (stopSubmit) {

      event.preventDefault();

    }

  }, false)

}



function checkFirstName(input) {

  let inputValue = input.value,

    errorMessage = "",

    letters = /^[a-zA-Z]+$/,

    characters = /^[a-zA-Z0-9!@#\$%\^\&*\)\(+=._-]+$/g;

  if (inputValue === null || inputValue === "") {

    errorMessage = "This field is empty.";

  }

  if (inputValue !== "") {

    if (inputValue.length < 3) {

      errorMessage = "This field has less than 3 characters.";

    }

    if (!inputValue.match(letters)) {

      errorMessage = "Numbers detected. Please write your first name.";

    }

    if (!inputValue.match(characters)) {

      errorMessage = "Special characters detected. Please write your first name.";

    }

  }

  renderErrorMessage(input, errorMessage);

  return errorMessage === "";


}



function checkLastName(input) {

  let inputValue = input.value,

    errorMessage = "",

    letters = /^[a-zA-Z]+$/,

    characters = /^[a-zA-Z0-9!@#\$%\^\&*\)\(+=._-]+$/g;

  if (inputValue === null || inputValue === "") {

    errorMessage = "This field is empty.";

  }

  if (inputValue !== "") {

    if (inputValue.length < 3) {

      errorMessage = "This field has less than 3 characters.";

    }

    if (!inputValue.match(letters)) {

      errorMessage = "Numbers detected. Please write your last name.";

    }

    if (!inputValue.match(characters)) {

      errorMessage = "Special characters detected. Please write your last name.";

    }

  }

  renderErrorMessage(input, errorMessage);

  return errorMessage === "";

}



function checkEmail(input) {

  let emailValue = input.value,

    errorMessage = "";

  let regex = /^(([^<>()\[\]\\.,;:\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,}))$/;

  if (!emailValue.match(regex)) {

    errorMessage = "Not a valid email address.";

  }

  if (emailValue === "") {

    errorMessage = "This field is empty.";

  }

  renderErrorMessage(input, errorMessage);

  return errorMessage === "";


}



function checkPhone(input) {

  let phoneValue = input.value,

    errorMessage = "";

  let regex = /^(((\+44\s?\d{4}|\(?0\d{4}\)?)\s?\d{3}\s?\d{3})|((\+44\s?\d{3}|\(?0\d{3}\)?)\s?\d{3}\s?\d{4})|((\+44\s?\d{2}|\(?0\d{2}\)?)\s?\d{4}\s?\d{4}))(\s?\#(\d{4}|\d{3}))?$/;

  if (!phoneValue.match(regex)) {

    errorMessage = "Not a valid UK phone number.";

  }

  if (isNaN(phoneValue)) {

    errorMessage = "No numbers detected. Please write a UK phone number.";

  }

  if (phoneValue === "") {

    errorMessage = "This field is empty.";

  }

  renderErrorMessage(input, errorMessage);

  return errorMessage === "";

}



function renderErrorMessage(selectedElem, errorMessage) {

  let errorElem = document.createElement("span");

  errorElem.setAttribute("class", "error");

  let errorText = document.createTextNode(errorMessage);

  errorElem.appendChild(errorText);

  selectedElem.parentNode.insertBefore(errorElem, selectedElem.nextSibling);

  return selectedElem;

}



function cleanUpErrors() {

  let indicator = document.getElementsByTagName("span");

  for (let i = 0; i < indicator.length; i++) {

    indicator[i].setAttribute("class", "hide");

  }

  const req = document.querySelectorAll("[required]")

  for (let i=0;i<req.length;i++) {

    req[i].classList.remove("errorBorder")

  }

}

label,

button {

  display: block;

  margin: 10px 0 5px 0;

}


input,

button {

  padding: 8px;

  width: 393px;

  font-size: 16px;

}


body,

button {

  font-family: Arial, sans-serif;

}


.error {

  color: #FFF;

  display: block;

  margin: 0 0 15px 0;

  background: #990000;

  padding: 5px 3px 5px 5px;

  width: 405px;

  line-height: 25px;

}


.hide {

  display: none;

  background: none;

}


.errorBorder {

  border-color:#990000

}

<!DOCTYPE html>

<html>


<head>

  <meta charset="UTF-8">

  <title>Personal Information Form</title>

  <script src="scripts/test5.js"></script>

  <link rel="stylesheet" href="css/test.css">

</head>


<body>

  <form id="form" action="test3success.html" novalidate="novalidate">

    <label for="firstName">First Name (required)</label>

    <input id="firstName" type="text" name="text" required>


    <label for="lastName">Last Name (required)</label>

    <input id="lastName" type="text" name="text" required>


    <label for="email">Email (required)</label>

    <input id="email" type="email" required>


    <label for="phone">Phone Number (required)</label>

    <input id="phone" type="tel" required>


    <button type="submit">Submit</button>

  </form>

</body>


</html>

實際上,由于這些字段被標記為必填,因此您可以將自定義消息添加到 HTML5 驗證中并讓它處理所有內容

工作正在進行中:

const letters = /^[a-zA-Z]+$/,

const characters = /^[a-zA-Z0-9!@#\$%\^\&*\)\(+=._-]+$/g;

const emailRe = /^(([^<>()\[\]\\.,;:\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,}))$/;

const phoneRe = /^(((\+44\s?\d{4}|\(?0\d{4}\)?)\s?\d{3}\s?\d{3})|((\+44\s?\d{3}|\(?0\d{3}\)?)\s?\d{3}\s?\d{4})|((\+44\s?\d{2}|\(?0\d{2}\)?)\s?\d{4}\s?\d{4}))(\s?\#(\d{4}|\d{3}))?$/;


window.addEventListener("load", function() {

  var elements = document.querySelectorAll("input[required]");

  for (let i = 0; i < elements.length; i++) {

        elements[i].oninvalid = function(e) {

            e.target.setCustomValidity("");

            if (!e.target.validity.valid) {

                e.target.setCustomValidity("This field cannot be left blank");

            }

        };

        elements[i].oninput = function(e) {

            

        };

    }

})



function checkName(input) {

  let inputValue = input.value,

    errorMessage = "",

    if (inputValue.length < 3) {

      this.setCustomValidity("This field has less than 3 characters.");

    }

    if (!inputValue.match(letters)) {

      this.setCustomValidity("Numbers detected. Please write a name.");

    }

    if (!inputValue.match(characters)) {

      this.setCustomValidity("Special characters detected. Please write a name.");

    }

}




function checkEmail(input) {

  let emailValue = input.value,

    errorMessage = "";

  if (!emailValue.match(emailRe)) {

    errorMessage = "Not a valid email address.";

  }

  if (emailValue === "") {

    errorMessage = "This field is empty.";

  }

  renderErrorMessage(input, errorMessage);

  return errorMessage === "";


}



function checkPhone(input) {

  let phoneValue = input.value,

    errorMessage = "";

  

  if (!phoneValue.match(phoneRe)) {

    errorMessage = "Not a valid UK phone number.";

  }

  if (isNaN(phoneValue)) {

    errorMessage = "No numbers detected. Please write a UK phone number.";

  }

  if (phoneValue === "") {

    errorMessage = "This field is empty.";

  }

  renderErrorMessage(input, errorMessage);

  return errorMessage === "";

}



function renderErrorMessage(selectedElem, errorMessage) {

  let errorElem = document.createElement("span");

  errorElem.setAttribute("class", "error");

  let errorText = document.createTextNode(errorMessage);

  errorElem.appendChild(errorText);

  selectedElem.parentNode.insertBefore(errorElem, selectedElem.nextSibling);

  return selectedElem;

}

label,

button {

  display: block;

  margin: 10px 0 5px 0;

}


input,

button {

  padding: 8px;

  width: 393px;

  font-size: 16px;

}


body,

button {

  font-family: Arial, sans-serif;

}


.error {

  color: #FFF;

  display: block;

  margin: 0 0 15px 0;

  background: #990000;

  padding: 5px 3px 5px 5px;

  width: 405px;

  line-height: 25px;

}


.hide {

  display: none;

  background: none;

}


.errorBorder {

  border-color:#990000

}

<!DOCTYPE html>

<html>


<head>

  <meta charset="UTF-8">

  <title>Personal Information Form</title>

  <script src="scripts/test5.js"></script>

  <link rel="stylesheet" href="css/test.css">

</head>


<body>

  <form id="form" action="test3success.html" novalidate="novalidate">

    <label for="firstName">First Name (required)</label>

    <input id="firstName" type="text" name="text" required>


    <label for="lastName">Last Name (required)</label>

    <input id="lastName" type="text" name="text" required>


    <label for="email">Email (required)</label>

    <input id="email" type="email" required>


    <label for="phone">Phone Number (required)</label>

    <input id="phone" type="tel" required>


    <button type="submit">Submit</button>

  </form>

</body>


</html>


查看完整回答
反對 回復 2023-10-04
  • 2 回答
  • 0 關注
  • 139 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號