Home > other >  Is there a way for listing errors from validity api?
Is there a way for listing errors from validity api?

Time:05-16

So i'm writing code for a contact form, and im trying to use validity api for the first time because adapting to wcag2.1 standards is hard. I have been able to get errors under each field while writing, but I also need a box that lists which field is invalid on top of the form when i submit.

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


    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() {
      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 }.`;
      }
      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'
      }
      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.'
      }
      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.`;
          }
          
      }

      // Set the styling appropriately
      emailError.className = 'error active';
      navnError.className = 'error active';
      telefonError.className = 'error active';
      messageError.className ='error active';
body {
    font: 1em sans-serif;
    width: 200px;
    padding: 0;
    margin : 0 auto;
  }

  p * {
    display: block;
  }

  input[type=email]{
    -webkit-appearance: none;
    appearance: none;

    width: 100%;
    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: 0;

    font-size: 80%;
    color: white;
    background-color: #900;
    border-radius: 0 0 5px 5px;

    box-sizing: border-box;
  }

  .error.active {
    padding: 0.3em;
  }
<!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>Detailed custom validation</title>
</head>

<body>
    <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>
    <form novalidate>
        <p>
          <label for="name">
            <span>Telefonnummer:</span>
            <input type="tel" id="telefon" name="telefon" required minlength="8">
            <span  aria-live="polite"></span>
          </label>
        </p>
        <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>
            <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>
    <button>Send</button>
  </form>
</div>
<script src="kontakt.js"></script>

</body>

</html>

Don't mind the css, i will code it over when integrating with our site.

CodePudding user response:

Consider creating a div element that wil contain the error list, placing it on top of the form.

Then you can easily integrate some code in your showError() function, in this example I simply checked the text content of the various error span element you already created, when error is present it gets mirrored on top of the form.

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')
    
    
    // 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(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(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(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>Message error!</p>'
      }
   }
      

      // Set the styling appropriately
      emailError.className = 'error active';
      navnError.className = 'error active';
      telefonError.className = 'error active';
      messageError.className ='error active';
body {
    font: 1em sans-serif;
    width: 200px;
    padding: 0;
    margin : 0 auto;
  }

  p * {
    display: block;
  }

  input[type=email]{
    -webkit-appearance: none;
    appearance: none;

    width: 100%;
    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: 0;

    font-size: 80%;
    color: white;
    background-color: #900;
    border-radius: 0 0 5px 5px;

    box-sizing: border-box;
  }

  .error.active {
    padding: 0.3em;
  }
<!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>Detailed custom validation</title>
</head>

<body>
    
    <!-- THIS DIV WILL CONTAIN ERROR MESSAGES -->
    <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>
    <form novalidate>
        <p>
          <label for="name">
            <span>Telefonnummer:</span>
            <input type="tel" id="telefon" name="telefon" required minlength="8">
            <span  aria-live="polite"></span>
          </label>
        </p>
        <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>
            <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>
    <button>Send</button>
  </form>
</div>
<script src="kontakt.js"></script>

</body>

</html>

  • Related