Удаление цвета фона тега span - PullRequest
0 голосов
/ 23 марта 2020

У меня есть проект, в котором мне нужно создать форму, которая проверяет каждый ввод и, если есть ошибка, он будет отображать сообщение. Если ошибки нет, сообщение не будет отображаться.

Я сделал это, но не могу удалить красный фон тега 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 === "";

}


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>

Ответы [ 2 ]

0 голосов
/ 23 марта 2020

Существует много повторений кода. Множественные функции проверки для разных полей имеют общий код, меняется только имя функции.

Вместо этого вы можете создать массив функций i: e const validationFunctions = [checkFirstName, checkLastName, checkEmail, checkPhone];

И затем вызвать функции, применяя л oop. span с классом 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>
0 голосов
/ 23 марта 2020

Использовать класс

С минимальными изменениями я добавляю класс по ошибке и удаляю класс из всех обязательных полей

Добавлен код

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 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>

На самом деле, поскольку поля помечены как обязательные, вы можете добавить пользовательские сообщения к проверке 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 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>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...