有没有办法在验证错误时更改 div 颜色?

Is there a way to change div color on validation error?

我一直在处理一个经过验证的联系表。我正在使用约束验证 api,并且我有这些文件,它们可以按我想要的方式工作,但我想知道是否有一种方法可以让错误框在出现错误时变为红色,而在没有错误时变为白色(或隐藏)验证错误。可能有些代码是不必要的,当我对功能感到满意时,我打算清理它,但现在看起来当一切都有效时我到处都有错误。

const form = document.getElementsByTagName('form')[0];
const email = document.getElementById('mail');
const emailError = document.querySelector('#mail + span.error');
const navn = document.getElementById('navn');
const navnError = document.querySelector('#navn + span.error');
const telefon = document.getElementById('telefon');
const telefonError = document.querySelector('#telefon + span.error')
const message = document.getElementById('message');
const messageError = document.querySelector('#message + span.error')
const personvern = document.getElementById('personvern');
const personvernError = document.querySelector('#personvern + span.error')


// THIS DIV WILL CONTAIN ERROR MESSAGES
const errOutput = document.querySelector('.errorsOutput')


email.addEventListener('input', function(event) {
  if (email.validity.valid) {
    emailError.innerHTML = '';
    emailError.className = 'error';
  } else {
    showError();
  }

});


navn.addEventListener('input', function(event) {

  if (navn.validity.valid) {
    navnError.innerHTML = '';
    navnError.className = 'error';

  } else {
    showError();
  }

})

telefon.addEventListener('input', function(event) {

  if (telefon.validity.valid) {
    telefonError.innerHTML = '';
    telefonError.className = 'error';

  } else {
    showError();
  }

})


message.addEventListener('input', function(event) {

  if (message.validity.valid) {
    messageError.innerHTML = '';
    messageError.className = 'error';

  } else {
    showError();
  }

})

form.addEventListener('submit', function(event) {

  if (!email.validity.valid || !navn.validity.valid || !telefon.validity.valid || !message.validity.valid) {
    showError();
    event.preventDefault();
  }

});



function showError() {

  // EMPTY ERRORS DIV
  errOutput.innerHTML = ''


  if (navn.validity.valueMissing) {
    navnError.textContent = '* Du må fylle inn navnet ditt';
  } else if (navn.validity.tooShort) {
    navnError.textContect = '* Du må fylle inn hele navnet ditt'
  }
  // OUTPUT ERRORS IN DIV

  if (navnError.textContent != '') {
    errOutput.innerHTML += '<p>Navn error!</p>'
  }

  if (email.validity.valueMissing) {

    emailError.textContent = '* Vennligst fyll inn e-posten din';
  } else if (email.validity.typeMismatch) {

    emailError.textContent = '* Dette er ikke en gyldig e-postadresse.';
  } else if (email.validity.tooShort) {

    emailError.textContent = `* Email should be at least ${ email.minLength } characters; you entered ${ email.value.length }.`;
  }
  // OUTPUT ERRORS IN DIV
  if (emailError.textContent != '') {
    errOutput.innerHTML += '<p>Email error!</p>'
  }



  if (telefon.validity.valueMissing) {
    telefonError.textContent = '* Du må fylle inn telefonnummeret ditt'
  } else if (telefon.validity.tooShort) {
    telefonError.textContent = '* Du mangler ett eller flere tall. Vennligst dobbeltsjekk.'
  }
  // OUTPUT ERRORS IN DIV
  if (telefonError.textContent != '') {
    errOutput.innerHTML += '<p>Telefonnummer error!</p>'
  }

  if (message.validity.valueMissing) {
    messageError.textContent = '* Beskjeden mangler, vennligst fyll inn'
  } else if (message.validity.tooShort) {
    messageError.textContent = `* Beskjed må være minst ${ message.minLength } tegn.`;
  }
  // OUTPUT ERRORS IN DIV
  if (messageError.textContent != '') {
    errOutput.innerHTML += '<p>Beskjed error!</p>'
  }
}


// Set the styling appropriately
emailError.className = 'error active';
navnError.className = 'error active';
telefonError.className = 'error active';
messageError.className = 'error active';
personvernError.className = 'error active';
body {
  width: 600px;
  padding: 0;
  margin: 0 auto;
  font-family: 'Open Sans', sans-serif;
  font-weight: 400;
  font-size: 1.1rem;
}

p * {
  display: block;
}

input[type=text] {
  -webkit-appearance: none;
  appearance: none;
  min-width: 500px;
  width: 100% !important;
  padding: 15px;
  border: 1px solid #333;
  margin: 0;
  font-family: inherit;
  font-size: 90%;
  box-sizing: border-box;
}

input[type=email] {
  -webkit-appearance: none;
  appearance: none;
  min-width: 500px;
  width: 100% !important;
  padding: 15px;
  border: 1px solid #333;
  margin: 0;
  font-family: inherit;
  font-size: 90%;
  box-sizing: border-box;
}

input[type=tel] {
  -webkit-appearance: none;
  appearance: none;
  min-width: 500px;
  width: 100% !important;
  padding: 15px;
  border: 1px solid #333;
  margin: 0;
  font-family: inherit;
  font-size: 90%;
  box-sizing: border-box;
}


/* This is our style for the invalid fields */

input:invalid {
  border-color: #900;
  background-color: #FDD;
}

input:focus:invalid {
  outline: none;
}


/* This is the style of our error messages */

.error {
  width: 100%;
  padding: 15px;
  min-height: 20px;
  font-size: 100%;
  color: white;
  background-color: #900;
  display: flex;
  justify-content: flex-start;
  margin: 1rem 0;
}

.error.active {
  padding: 0;
}

.errorsOutput {
  background-color: #ac0606;
  color: white;
  margin: 0 0 5px 0;
}

.errorsOutput p {
  padding: 1px;
}
<!DOCTYPE html>
<html>

<head>
  <script src="jquery-3.6.0.min.js"></script>
  <script src="kontaktskjema.js"></script>
  <link rel="stylesheet" href="kontakt.css">
  <meta charset="utf-8">
  <title>Kontaktskjema</title>
</head>

<body>

  <!-- THIS DIV WILL CONTAIN ERROR MESSAGES -->
  <div class="errorsOutput">
  </div>

  <div class="kontaktskjema">
    <div class="error">
      <form novalidate>
        <p>
          <label for="navn">
          <span>Navn:</span>
        <input type="text" id="navn" name="navn" required minlength="3">
        <span class="error" aria-live="polite"></span>
      </label>
        </p>
    </div>
    <div class="error">
      <form novalidate>
        <p>
          <label for="name">
            <span>Telefonnummer:</span>
            <input type="tel" id="telefon" name="telefon" required minlength="8" required maxlength="8">
            <span class="error" aria-live="polite"></span>
          </label>
        </p>
    </div>
    <div class="error">
      <form novalidate>
        <p>
          <label for="mail">
                <span>E-post:</span>
                <input type="email" id="mail" name="mail" required minlength="6">
                <span class="error" aria-live="polite"></span>
              </label>
        </p>
    </div>
    <div class="error">
      <form novalidate>
        <p>
          <label for="message">
                    <span>Beskjed:</span>
                    <input type="text" id="message" name="message" required minlength="10">
                    <span class="error" aria-live="polite"></span>
                  </label>
        </p>
    </div>
    <form>
      <p>
        <label for="personvern">
                      <div class="personvern">
                      <span>Personvern:</span>
                      <br>
                      <input type="checkbox" id="personvern" name="personvern" required>
                      <span>Jeg har lest og godkjent <a href="https://demo2108.mobilpluss.no/ac/personvern">Personvernserklæringen</a></span>
                      <span class="error" aria-live="polite"></span>
                    </div>
                    </label>
      </p>

      <button>Send</button>
    </form>
  </div>
  <script src="kontakt.js"></script>

</body>

</html>

谢谢!

我的方法是通过 application-defined 元素属性。

CSS完全支持attribute selectors。如果您将 div 元素的某些属性设置为某个值,比如 data-validation-error=true,那么在您的 CSS

div[data-validation-error="true"] {
   /* red */
}

div[data-validation-error="ok"] {
  display: none; /* hidden */
}

并在JavaScript中,对您要控制的div使用setAttribute功能。

注意我使用了 data- 前缀。这是 user/application-defined 属性的标准 HTML 属性前缀。