[英]Removing span tag background colour
I have a project where I need to create a form that validates each input and if there's an error, it will display the message.我有一个项目,我需要创建一个表单来验证每个输入,如果出现错误,它将显示消息。 If there's no error, no message will be displayed.
如果没有错误,则不会显示任何消息。
I've done it but I can't seem to remove the red background of the span tag every time there's no error.我已经完成了,但每次没有错误时,我似乎无法删除 span 标签的红色背景。
In the cleanUpErrors()
I tried to use indicator[i].remove();
在
cleanUpErrors()
我尝试使用indicator[i].remove();
and indicator[i].setAttribute("class", "hide");
和
indicator[i].setAttribute("class", "hide");
but none of them work.但它们都不起作用。
There shouldn't be any red background once there's no error message.一旦没有错误消息,就不应该有任何红色背景。
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 === ""; } 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"); } }
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; }
<!DOCTYPE html> <html lang="en"> <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>
Use a class使用类
With minimum changes, I add the class on error and remove the class from all required fields以最少的更改,我添加错误的类并从所有必填字段中删除该类
Added code添加代码
theForm[X].classList.add("errorBorder")
and和
const req = document.querySelectorAll("[required]")
for (let i=0;i<req.length;i++) {
req[i].classList.remove("errorBorder")
}
I would also toggle the class on the error spans.我还会在错误范围上切换类。
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 lang="en"> <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>
Actually, since the fields are marked required, you can add custom messages to the HTML5 validation and have that handle it all实际上,由于字段被标记为必填,您可以向 HTML5 验证添加自定义消息并让其处理所有内容
work in progress:工作正在进行中:
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 lang="en"> <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>
There is lot of code repetition.有很多代码重复。 The multiple validation functions for different fields have common code, only the function name is changing.
不同字段的多个验证函数有共同的代码,只是函数名称发生了变化。
Instead you can create an array of functions i:e const validationFunctions = [checkFirstName, checkLastName, checkEmail, checkPhone];
相反,您可以创建一个函数数组,即:
const validationFunctions = [checkFirstName, checkLastName, checkEmail, checkPhone];
And then call the functions applying loop.然后调用应用循环的函数。 The
span
with class error
will only be removed if the condition required
is satisfied.只有满足
required
的条件,才会删除具有类error
的span
。
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.