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

Time:05-31

I've been working on a contact form with validation. Im using constraint validation api, and I have these files which kinda works the way I want, but I wonder if there's a way I can make the errorboxes red when there's an error, and white (or hidden) when there's no validation error. There's probably some code which is unneccesary, and I plan to clean it up when i'm satisfied with the functionality, but now it looks like i have errors everywhere when everything is valid.

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

  <div >
    <div >
      <form novalidate>
        <p>
          <label for="navn">
          <span>Navn:</span>
        <input type="text" id="navn" name="navn" required minlength="3">
        <span  aria-live="polite"></span>
      </label>
        </p>
    </div>
    <div >
      <form novalidate>
        <p>
          <label for="name">
            <span>Telefonnummer:</span>
            <input type="tel" id="telefon" name="telefon" required minlength="8" required maxlength="8">
            <span  aria-live="polite"></span>
          </label>
        </p>
    </div>
    <div >
      <form novalidate>
        <p>
          <label for="mail">
                <span>E-post:</span>
                <input type="email" id="mail" name="mail" required minlength="6">
                <span  aria-live="polite"></span>
              </label>
        </p>
    </div>
    <div >
      <form novalidate>
        <p>
          <label for="message">
                    <span>Beskjed:</span>
                    <input type="text" id="message" name="message" required minlength="10">
                    <span  aria-live="polite"></span>
                  </label>
        </p>
    </div>
    <form>
      <p>
        <label for="personvern">
                      <div >
                      <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  aria-live="polite"></span>
                    </div>
                    </label>
      </p>

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

</body>

</html>

Thanks!

CodePudding user response:

The way I'd do it, is through application-defined element attributes.

CSS totally support attribute selectors. If you set some attribute of the div element to a certain value, say data-validation-error=true, then in your CSS

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

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

and in JavaScript, use the setAttribute function on the div you want to control.

Notice I used the data- prefix. This is the standard HTML attribute prefix for user/application-defined attributes.

  • Related