Form validation

In this simple case you might not even need JS but only CSS:

.error {
  display: none;
}

input:invalid + .error {
  display: initial;
}

This will only show .error elements right next to an invalid input element. If you do want to use JS (e.g. for displaying specific error messages based on the type of (in)validity), you can do it like this:

.error {
  display: none;
}

.error.active {
  display: initial;
}
<form id="my-form">
  <label>
    Username
    <input type="text" required>
    <span class="error">Please enter a username</span>
  </label>

  <label>
    Password
    <input type="text" required>
    <span class="error">Please enter a password</span>
  </label>
</form>
var myForm = document.getElementById('my-form')

// Use event delegation so that we don't have to add an
// event listener to each input separately
myForm.addEventListener('input', function (event) {
  var target = event.target
  var validity = target.validity

  // Get the error element wrapped in the same label
  // as the input element itself
  var errorEl = target.parentNode.querySelector('.error')

  // Toggle the active class depending on the validity state;
  // we might also handle different cases here
  if (errorEl) {
    errorEl.classList.toggle('active', !validity.valid)
  }
})

PS: Just occurred to me that another good reason for using JS here is that it doesn’t show the error messages as long as the corresponding input elements are in a “pristine” state, but only when the user actually entered something invalid.

2 Likes