Jump to navigation

Form Validation

Example Attributes

Required

<input id="name" name="name" required>

Min/Max width

<input id="name" name="name" required minlength="6" maxlength="7">

Tell form not to validate

<form novalidate>

CSS classes

.email:valid {
  background-color: green;
}

.email:invalid {
  background-color: red;
}

The constraint validation API

<input type="email" id="mail" name="mail">
var email = document.getElementById("mail");

email.addEventListener("input", function (event) {
  // Check if element valid, returns boolean
  checkValidity();
  // Check validationMessage
  email.validationMessage
  // returns object  giving details on validation
  email.validity
  // Returns true if element will be  validated on form submission
  email.willValidate
  // Change the error message
  if (email.validity.typeMismatch) {
    email.setCustomValidity("I expect an e-mail, darling!");
  } else {
    email.setCustomValidity("");
  }
});

Example Form

<form novalidate>
  <label for="mail">
      <span>Please enter an email address:</span>
      <input type="email" id="mail" name="mail">
      <span class="error" aria-live="polite"></span>
    </label>
  <button>Submit</button>  
</form>
var form  = document.getElementsByTagName('form')[0];
var email = document.getElementById('mail');
var error = document.querySelector('.error');

email.addEventListener("input", () => {
  console.log(email.value.length);
  if (email.validity.valid) {
    error.innerHTML = "";
    error.className = "error";
  }
});

form.addEventListener("submit", (event) => {
  if (!email.validity.valid || !email.value.length) {
    error.innerHTML = "Email required";
    error.className = "error active";
    email.focus();
    event.preventDefault();
  }
});

See the Pen Example using the constraint validation API by Shane Prendergast (@webknit) on CodePen.

Refs