Validate a form before sending

Use the browser’s built-in Constraint Validation API. Repeat the checks on the server; this only improves the experience.

JavaScript · Validate a form before sendingBeginner
const form = document.querySelector('#signup');

form.addEventListener('submit', (e) => {
  if (!form.checkValidity()) {
    e.preventDefault();
    form.reportValidity();          // shows the browser's own messages
    return;
  }
  // extra rule
  const pw = form.elements.password.value;
  if (pw.length < 12) {
    e.preventDefault();
    form.elements.password.setCustomValidity('Use at least 12 characters.');
    form.reportValidity();
    form.elements.password.setCustomValidity('');   // reset so it can be corrected
  }
});
formsvalidationconstraint api