Vanilla JavaScript Form Validation

Validate HTML forms with vanilla JavaScript using the Constraint Validation API. Provides custom error messages, real-time validation on input, and.

JavascriptForm Validation

Code

snippet
function validateForm(form) {
  const fields = form.querySelectorAll('input, textarea, select');
  let isValid = true;

  fields.forEach((field) => {
    const errorEl = form.querySelector(`[data-error-for="${field.name}"]`);
    if (!field.checkValidity()) {
      isValid = false;
      if (errorEl) errorEl.textContent = field.validationMessage;
      field.setAttribute('aria-invalid', 'true');
    } else {
      if (errorEl) errorEl.textContent = '';
      field.removeAttribute('aria-invalid');
    }
  });

  return isValid;
}

const form = document.querySelector('form');
form.addEventListener('input', (e) => validateForm(e.currentTarget));
form.addEventListener('submit', (e) => {
  if (!validateForm(form)) e.preventDefault();
});

How the snippet works

Vanilla JavaScript Form Validation keeps everything in the function validateForm.

Watch out for

  • The snippet leans on document — browser-only surfaces a bare Node process cannot provide.

Using it

The primary signature is function validateForm(form)

Key statements

form.addEventListener('input', (e) => validateForm(e.currentTarget));
form.addEventListener('submit', (e) => {
  if (!validateForm(form)) e.preventDefault();
});

Interactive Tools for This Topic

FAQ

Does Vanilla JavaScript Form Validation run in plain Node.js?
No — it touches `document`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.