删除跨度标签背景颜色

我有一个项目,我需要创建一个表单来验证每个输入,如果出现错误,它将显示消息。如果没有错误,则不会显示任何消息。

我已经做到了,但每次没有错误时,我似乎无法删除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 === "";


}

不负相思意
浏览 89回答 2
2回答

慕尼黑的夜晚无繁华

有很多代码重复。不同字段的多个验证函数具有共同的代码,只是函数名称发生变化。相反,您可以创建一个函数数组 i:econst validationFunctions = [checkFirstName, checkLastName, checkEmail, checkPhone];然后调用应用循环的函数。仅当满足条件时, withspan类error才会被删除。requiredconst validationFunctions = [checkFirstName, checkLastName, checkEmail, checkPhone];validationFunctions.forEach((fun, i) => {&nbsp; &nbsp; if(!fun(theForm[i])) {&nbsp; &nbsp; &nbsp; &nbsp; theForm[i].style.borderColor = "#990000";&nbsp; &nbsp; &nbsp; &nbsp; stopSubmit = true;&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp;document.querySelector(`#${theForm[i].id}`).nextElementSibling.style.display = "none";&nbsp; &nbsp;}});window.onload = function() {&nbsp; let theForm = document.getElementById("form");&nbsp; theForm.addEventListener("submit", function(event) {&nbsp; &nbsp; event.preventDefault();&nbsp; &nbsp; let stopSubmit = false;&nbsp; &nbsp; const validationFunctions = [checkFirstName, checkLastName, checkEmail, checkPhone];&nbsp; &nbsp; validationFunctions.forEach((fun, i) => {&nbsp; &nbsp; &nbsp; if (!fun(theForm[i])) {&nbsp; &nbsp; &nbsp; &nbsp; theForm[i].style.borderColor = "#990000";&nbsp; &nbsp; &nbsp; &nbsp; stopSubmit = true;&nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; document.querySelector(`#${theForm[i].id}`).nextElementSibling.style.display = "none";&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; });&nbsp; &nbsp; if (stopSubmit) {&nbsp; &nbsp; &nbsp; event.preventDefault();&nbsp; &nbsp; }&nbsp; }, false)}function checkFirstName(input) {&nbsp; let inputValue = input.value,&nbsp; &nbsp; errorMessage = "",&nbsp; &nbsp; letters = /^[a-zA-Z]+$/,&nbsp; &nbsp; characters = /^[a-zA-Z0-9!@#\$%\^\&*\)\(+=._-]+$/g;&nbsp; if (inputValue === null || inputValue === "") {&nbsp; &nbsp; errorMessage = "This field is empty.";&nbsp; }&nbsp; if (inputValue !== "") {&nbsp; &nbsp; if (inputValue.length < 3) {&nbsp; &nbsp; &nbsp; errorMessage = "This field has less than 3 characters.";&nbsp; &nbsp; }&nbsp; &nbsp; if (!inputValue.match(letters)) {&nbsp; &nbsp; &nbsp; errorMessage = "Numbers detected. Please write your first name.";&nbsp; &nbsp; }&nbsp; &nbsp; if (!inputValue.match(characters)) {&nbsp; &nbsp; &nbsp; errorMessage = "Special characters detected. Please write your first name.";&nbsp; &nbsp; }&nbsp; }&nbsp; if (input.nextElementSibling.tagName !== 'SPAN') {&nbsp; &nbsp; renderErrorMessage(input, errorMessage);&nbsp; }&nbsp; return errorMessage === "";}function checkLastName(input) {&nbsp; let inputValue = input.value,&nbsp; &nbsp; errorMessage = "",&nbsp; &nbsp; letters = /^[a-zA-Z]+$/,&nbsp; &nbsp; characters = /^[a-zA-Z0-9!@#\$%\^\&*\)\(+=._-]+$/g;&nbsp; if (inputValue === null || inputValue === "") {&nbsp; &nbsp; errorMessage = "This field is empty.";&nbsp; }&nbsp; if (inputValue !== "") {&nbsp; &nbsp; if (inputValue.length < 3) {&nbsp; &nbsp; &nbsp; errorMessage = "This field has less than 3 characters.";&nbsp; &nbsp; }&nbsp; &nbsp; if (!inputValue.match(letters)) {&nbsp; &nbsp; &nbsp; errorMessage = "Numbers detected. Please write your last name.";&nbsp; &nbsp; }&nbsp; &nbsp; if (!inputValue.match(characters)) {&nbsp; &nbsp; &nbsp; errorMessage = "Special characters detected. Please write your last name.";&nbsp; &nbsp; }&nbsp; }&nbsp; if (input.nextElementSibling.tagName !== 'SPAN') {&nbsp; &nbsp; renderErrorMessage(input, errorMessage);&nbsp; }&nbsp; return errorMessage === "";}function checkEmail(input) {&nbsp; let emailValue = input.value,&nbsp; &nbsp; errorMessage = "";&nbsp; 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,}))$/;&nbsp; if (!emailValue.match(regex)) {&nbsp; &nbsp; errorMessage = "Not a valid email address.";&nbsp; }&nbsp; if (emailValue === "") {&nbsp; &nbsp; errorMessage = "This field is empty.";&nbsp; }&nbsp; if (input.nextElementSibling.tagName !== 'SPAN') {&nbsp; &nbsp; renderErrorMessage(input, errorMessage);&nbsp; }&nbsp; return errorMessage === "";}function checkPhone(input) {&nbsp; let phoneValue = input.value,&nbsp; &nbsp; errorMessage = "";&nbsp; 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}))?$/;&nbsp; if (!phoneValue.match(regex)) {&nbsp; &nbsp; errorMessage = "Not a valid UK phone number.";&nbsp; }&nbsp; if (isNaN(phoneValue)) {&nbsp; &nbsp; errorMessage = "No numbers detected. Please write a UK phone number.";&nbsp; }&nbsp; if (phoneValue === "") {&nbsp; &nbsp; errorMessage = "This field is empty.";&nbsp; }&nbsp; if (input.nextElementSibling.tagName !== 'SPAN') {&nbsp; &nbsp; renderErrorMessage(input, errorMessage);&nbsp; }&nbsp; return errorMessage === "";}function renderErrorMessage(selectedElem, errorMessage) {&nbsp; let errorElem = document.createElement("span");&nbsp; errorElem.setAttribute("class", "error");&nbsp; let errorText = document.createTextNode(errorMessage);&nbsp; errorElem.appendChild(errorText);&nbsp; selectedElem.parentNode.insertBefore(errorElem, selectedElem.nextSibling);&nbsp; return selectedElem;}label,button {&nbsp; display: block;&nbsp; margin: 10px 0 5px 0;}input,button {&nbsp; padding: 8px;&nbsp; width: 393px;&nbsp; font-size: 16px;}body,button {&nbsp; font-family: Arial, sans-serif;}.error {&nbsp; color: #FFF;&nbsp; display: block;&nbsp; margin: 0 0 15px 0;&nbsp; background: #990000;&nbsp; padding: 5px 3px 5px 5px;&nbsp; width: 405px;&nbsp; line-height: 25px;}.hide {&nbsp; display: none;&nbsp; /* background: none; */}<form id="form" action="test3success.html" novalidate="novalidate">&nbsp; <label for="firstName">First Name (required)</label>&nbsp; <input id="firstName" type="text" name="text" required>&nbsp; <label for="lastName">Last Name (required)</label>&nbsp; <input id="lastName" type="text" name="text" required>&nbsp; <label for="email">Email (required)</label>&nbsp; <input id="email" type="email" required>&nbsp; <label for="phone">Phone Number (required)</label>&nbsp; <input id="phone" type="tel" required>&nbsp; <button type="submit">Submit</button></form>

子衿沉夜

使用一个类通过最少的更改,我在错误时添加类并从所有必填字段中删除该类添加了代码theForm[X].classList.add("errorBorder")和const req = document.querySelectorAll("[required]")for (let i=0;i<req.length;i++) {&nbsp; req[i].classList.remove("errorBorder")}我还会在错误跨度上切换类。window.onload = function() {&nbsp; let theForm = document.getElementById("form");&nbsp; theForm.addEventListener("submit", function(event) {&nbsp; &nbsp; let stopSubmit = false;&nbsp; &nbsp; cleanUpErrors();&nbsp; &nbsp; if (!checkFirstName(theForm[0])) {&nbsp; &nbsp; &nbsp; theForm[0].classList.add("errorBorder")&nbsp; &nbsp; &nbsp; stopSubmit = true;&nbsp; &nbsp; }&nbsp; &nbsp; if (!checkLastName(theForm[1])) {&nbsp; &nbsp; &nbsp; theForm[1].classList.add("errorBorder")&nbsp; &nbsp; &nbsp; stopSubmit = true;&nbsp; &nbsp; }&nbsp; &nbsp; if (!checkEmail(theForm[2])) {&nbsp; &nbsp; &nbsp; theForm[2].classList.add("errorBorder")&nbsp; &nbsp; &nbsp; stopSubmit = true;&nbsp; &nbsp; }&nbsp; &nbsp; if (!checkPhone(theForm[3])) {&nbsp; &nbsp; &nbsp; theForm[3].classList.add("errorBorder")&nbsp; &nbsp; &nbsp; stopSubmit = true;&nbsp; &nbsp; }&nbsp; &nbsp; if (stopSubmit) {&nbsp; &nbsp; &nbsp; event.preventDefault();&nbsp; &nbsp; }&nbsp; }, false)}function checkFirstName(input) {&nbsp; let inputValue = input.value,&nbsp; &nbsp; errorMessage = "",&nbsp; &nbsp; letters = /^[a-zA-Z]+$/,&nbsp; &nbsp; characters = /^[a-zA-Z0-9!@#\$%\^\&*\)\(+=._-]+$/g;&nbsp; if (inputValue === null || inputValue === "") {&nbsp; &nbsp; errorMessage = "This field is empty.";&nbsp; }&nbsp; if (inputValue !== "") {&nbsp; &nbsp; if (inputValue.length < 3) {&nbsp; &nbsp; &nbsp; errorMessage = "This field has less than 3 characters.";&nbsp; &nbsp; }&nbsp; &nbsp; if (!inputValue.match(letters)) {&nbsp; &nbsp; &nbsp; errorMessage = "Numbers detected. Please write your first name.";&nbsp; &nbsp; }&nbsp; &nbsp; if (!inputValue.match(characters)) {&nbsp; &nbsp; &nbsp; errorMessage = "Special characters detected. Please write your first name.";&nbsp; &nbsp; }&nbsp; }&nbsp; renderErrorMessage(input, errorMessage);&nbsp; return errorMessage === "";}function checkLastName(input) {&nbsp; let inputValue = input.value,&nbsp; &nbsp; errorMessage = "",&nbsp; &nbsp; letters = /^[a-zA-Z]+$/,&nbsp; &nbsp; characters = /^[a-zA-Z0-9!@#\$%\^\&*\)\(+=._-]+$/g;&nbsp; if (inputValue === null || inputValue === "") {&nbsp; &nbsp; errorMessage = "This field is empty.";&nbsp; }&nbsp; if (inputValue !== "") {&nbsp; &nbsp; if (inputValue.length < 3) {&nbsp; &nbsp; &nbsp; errorMessage = "This field has less than 3 characters.";&nbsp; &nbsp; }&nbsp; &nbsp; if (!inputValue.match(letters)) {&nbsp; &nbsp; &nbsp; errorMessage = "Numbers detected. Please write your last name.";&nbsp; &nbsp; }&nbsp; &nbsp; if (!inputValue.match(characters)) {&nbsp; &nbsp; &nbsp; errorMessage = "Special characters detected. Please write your last name.";&nbsp; &nbsp; }&nbsp; }&nbsp; renderErrorMessage(input, errorMessage);&nbsp; return errorMessage === "";}function checkEmail(input) {&nbsp; let emailValue = input.value,&nbsp; &nbsp; errorMessage = "";&nbsp; 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,}))$/;&nbsp; if (!emailValue.match(regex)) {&nbsp; &nbsp; errorMessage = "Not a valid email address.";&nbsp; }&nbsp; if (emailValue === "") {&nbsp; &nbsp; errorMessage = "This field is empty.";&nbsp; }&nbsp; renderErrorMessage(input, errorMessage);&nbsp; return errorMessage === "";}function checkPhone(input) {&nbsp; let phoneValue = input.value,&nbsp; &nbsp; errorMessage = "";&nbsp; 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}))?$/;&nbsp; if (!phoneValue.match(regex)) {&nbsp; &nbsp; errorMessage = "Not a valid UK phone number.";&nbsp; }&nbsp; if (isNaN(phoneValue)) {&nbsp; &nbsp; errorMessage = "No numbers detected. Please write a UK phone number.";&nbsp; }&nbsp; if (phoneValue === "") {&nbsp; &nbsp; errorMessage = "This field is empty.";&nbsp; }&nbsp; renderErrorMessage(input, errorMessage);&nbsp; return errorMessage === "";}function renderErrorMessage(selectedElem, errorMessage) {&nbsp; let errorElem = document.createElement("span");&nbsp; errorElem.setAttribute("class", "error");&nbsp; let errorText = document.createTextNode(errorMessage);&nbsp; errorElem.appendChild(errorText);&nbsp; selectedElem.parentNode.insertBefore(errorElem, selectedElem.nextSibling);&nbsp; return selectedElem;}function cleanUpErrors() {&nbsp; let indicator = document.getElementsByTagName("span");&nbsp; for (let i = 0; i < indicator.length; i++) {&nbsp; &nbsp; indicator[i].setAttribute("class", "hide");&nbsp; }&nbsp; const req = document.querySelectorAll("[required]")&nbsp; for (let i=0;i<req.length;i++) {&nbsp; &nbsp; req[i].classList.remove("errorBorder")&nbsp; }}label,button {&nbsp; display: block;&nbsp; margin: 10px 0 5px 0;}input,button {&nbsp; padding: 8px;&nbsp; width: 393px;&nbsp; font-size: 16px;}body,button {&nbsp; font-family: Arial, sans-serif;}.error {&nbsp; color: #FFF;&nbsp; display: block;&nbsp; margin: 0 0 15px 0;&nbsp; background: #990000;&nbsp; padding: 5px 3px 5px 5px;&nbsp; width: 405px;&nbsp; line-height: 25px;}.hide {&nbsp; display: none;&nbsp; background: none;}.errorBorder {&nbsp; border-color:#990000}<!DOCTYPE html><html><head>&nbsp; <meta charset="UTF-8">&nbsp; <title>Personal Information Form</title>&nbsp; <script src="scripts/test5.js"></script>&nbsp; <link rel="stylesheet" href="css/test.css"></head><body>&nbsp; <form id="form" action="test3success.html" novalidate="novalidate">&nbsp; &nbsp; <label for="firstName">First Name (required)</label>&nbsp; &nbsp; <input id="firstName" type="text" name="text" required>&nbsp; &nbsp; <label for="lastName">Last Name (required)</label>&nbsp; &nbsp; <input id="lastName" type="text" name="text" required>&nbsp; &nbsp; <label for="email">Email (required)</label>&nbsp; &nbsp; <input id="email" type="email" required>&nbsp; &nbsp; <label for="phone">Phone Number (required)</label>&nbsp; &nbsp; <input id="phone" type="tel" required>&nbsp; &nbsp; <button type="submit">Submit</button>&nbsp; </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() {&nbsp; var elements = document.querySelectorAll("input[required]");&nbsp; for (let i = 0; i < elements.length; i++) {&nbsp; &nbsp; &nbsp; &nbsp; elements[i].oninvalid = function(e) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; e.target.setCustomValidity("");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (!e.target.validity.valid) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; e.target.setCustomValidity("This field cannot be left blank");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; };&nbsp; &nbsp; &nbsp; &nbsp; elements[i].oninput = function(e) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; };&nbsp; &nbsp; }})function checkName(input) {&nbsp; let inputValue = input.value,&nbsp; &nbsp; errorMessage = "",&nbsp; &nbsp; if (inputValue.length < 3) {&nbsp; &nbsp; &nbsp; this.setCustomValidity("This field has less than 3 characters.");&nbsp; &nbsp; }&nbsp; &nbsp; if (!inputValue.match(letters)) {&nbsp; &nbsp; &nbsp; this.setCustomValidity("Numbers detected. Please write a name.");&nbsp; &nbsp; }&nbsp; &nbsp; if (!inputValue.match(characters)) {&nbsp; &nbsp; &nbsp; this.setCustomValidity("Special characters detected. Please write a name.");&nbsp; &nbsp; }}function checkEmail(input) {&nbsp; let emailValue = input.value,&nbsp; &nbsp; errorMessage = "";&nbsp; if (!emailValue.match(emailRe)) {&nbsp; &nbsp; errorMessage = "Not a valid email address.";&nbsp; }&nbsp; if (emailValue === "") {&nbsp; &nbsp; errorMessage = "This field is empty.";&nbsp; }&nbsp; renderErrorMessage(input, errorMessage);&nbsp; return errorMessage === "";}function checkPhone(input) {&nbsp; let phoneValue = input.value,&nbsp; &nbsp; errorMessage = "";&nbsp;&nbsp;&nbsp; if (!phoneValue.match(phoneRe)) {&nbsp; &nbsp; errorMessage = "Not a valid UK phone number.";&nbsp; }&nbsp; if (isNaN(phoneValue)) {&nbsp; &nbsp; errorMessage = "No numbers detected. Please write a UK phone number.";&nbsp; }&nbsp; if (phoneValue === "") {&nbsp; &nbsp; errorMessage = "This field is empty.";&nbsp; }&nbsp; renderErrorMessage(input, errorMessage);&nbsp; return errorMessage === "";}function renderErrorMessage(selectedElem, errorMessage) {&nbsp; let errorElem = document.createElement("span");&nbsp; errorElem.setAttribute("class", "error");&nbsp; let errorText = document.createTextNode(errorMessage);&nbsp; errorElem.appendChild(errorText);&nbsp; selectedElem.parentNode.insertBefore(errorElem, selectedElem.nextSibling);&nbsp; return selectedElem;}label,button {&nbsp; display: block;&nbsp; margin: 10px 0 5px 0;}input,button {&nbsp; padding: 8px;&nbsp; width: 393px;&nbsp; font-size: 16px;}body,button {&nbsp; font-family: Arial, sans-serif;}.error {&nbsp; color: #FFF;&nbsp; display: block;&nbsp; margin: 0 0 15px 0;&nbsp; background: #990000;&nbsp; padding: 5px 3px 5px 5px;&nbsp; width: 405px;&nbsp; line-height: 25px;}.hide {&nbsp; display: none;&nbsp; background: none;}.errorBorder {&nbsp; border-color:#990000}<!DOCTYPE html><html><head>&nbsp; <meta charset="UTF-8">&nbsp; <title>Personal Information Form</title>&nbsp; <script src="scripts/test5.js"></script>&nbsp; <link rel="stylesheet" href="css/test.css"></head><body>&nbsp; <form id="form" action="test3success.html" novalidate="novalidate">&nbsp; &nbsp; <label for="firstName">First Name (required)</label>&nbsp; &nbsp; <input id="firstName" type="text" name="text" required>&nbsp; &nbsp; <label for="lastName">Last Name (required)</label>&nbsp; &nbsp; <input id="lastName" type="text" name="text" required>&nbsp; &nbsp; <label for="email">Email (required)</label>&nbsp; &nbsp; <input id="email" type="email" required>&nbsp; &nbsp; <label for="phone">Phone Number (required)</label>&nbsp; &nbsp; <input id="phone" type="tel" required>&nbsp; &nbsp; <button type="submit">Submit</button>&nbsp; </form></body></html>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Html5