← Tous les articles

Form validation without a library: the Constraint Validation API

The required, type and min attributes already do half the job. The Constraint Validation API lets you show your own accessible error messages without adding a dependency.

Form validation without a library: the Constraint Validation API

Key points

  • HTML attributes (required, type, min, pattern) stay the single source of truth for rules.
  • novalidate turns off the browser’s bubbles, not validation itself.
  • Forget to call setCustomValidity(”) and the field stays invalid for good.

A client wanted clearer error messages on their quote request form than the browser’s native bubbles, which look different in every browser. The knee-jerk reaction would have been to add a validation library and rewrite every rule in JavaScript. You don’t need to: the browser already knows how to validate the form. You just need to take over how errors are displayed.

Keep the rules in your HTML

Constraints stay in the markup, where they’re easy to read and still work if the script fails to load. The novalidate attribute on the form only removes the native bubbles; fields are still evaluated.

<form id="quote" novalidate>
  <label for="email">E-mail</label>
  <input id="email" name="email" type="email" required aria-describedby="email-error">
  <p id="email-error" class="field-error" hidden></p>

  <label for="budget">Budget (EUR)</label>
  <input id="budget" name="budget" type="number" min="500" step="50" required
         aria-describedby="budget-error">
  <p id="budget-error" class="field-error" hidden></p>

  <button>Send</button>
</form>

Each field points to its error container through aria-describedby, so screen readers announce the message along with the label.

Read validity and display your own messages

Every field exposes a validity object with one boolean per kind of error: valueMissing, typeMismatch, rangeUnderflow, patternMismatch and so on. Map a message to each:

const form = document.querySelector('#quote');

const messages = {
  valueMissing: 'This field is required.',
  typeMismatch: 'Please enter a valid email address.',
  rangeUnderflow: 'Our projects start at 500 EUR.',
  stepMismatch: 'Please round to the nearest 50 EUR.',
};

function showError(field) {
  const box = document.getElementById(field.getAttribute('aria-describedby'));
  if (!box) return; // e.g. the submit button
  const key = Object.keys(messages).find((k) => field.validity[k]);
  box.textContent = key ? messages[key] : field.validationMessage;
  box.hidden = field.validity.valid;
  field.setAttribute('aria-invalid', String(!field.validity.valid));
}

form.addEventListener('submit', (e) => {
  if (!form.checkValidity()) {
    e.preventDefault();
    [...form.elements].filter((el) => el.willValidate).forEach(showError);
    form.querySelector(':invalid')?.focus();
  }
});

// Re-check a field once the user leaves it
form.addEventListener('focusout', (e) => {
  if (e.target.willValidate) showError(e.target);
});

We show errors on submit and when the user leaves a field, never while they type. An “invalid address” warning that pops up after the first character is more irritating than helpful. Falling back to validationMessage covers anything you didn’t plan for, using the browser’s wording in the user’s language.

Business rules with setCustomValidity()

For a rule HTML can’t express, setCustomValidity() marks the field invalid with your message. The classic trap, which we’ve fixed in more than one inherited codebase, is never clearing it. The field then stays invalid even after the user corrects it, and the form simply won’t submit.

const email = form.elements.email;

email.addEventListener('input', () => {
  // Always reset first, or the field stays invalid forever
  email.setCustomValidity('');
  if (email.value.endsWith('@example.com')) {
    email.setCustomValidity('Please use your work address.');
  }
});

Here validity.customError is true and your message comes back through validationMessage, which the showError fallback above already handles.

Styling, and what client-side validation doesn’t replace

The :user-invalid pseudo-class only kicks in after the user has interacted with a field, unlike :invalid, which paints an empty form red the moment it loads:

input:user-invalid { border-color: #b91c1c; }
.field-error { color: #b91c1c; font-size: .875rem; }

One last point, and it matters: all of this improves the experience, not security. Anyone can send a request without touching your page. The same rules must be enforced on the server, and the server always has the final say.

FAQ

Do I still need a validation library?

For a typical form, rarely. A library makes sense for complex cross-field rules, or when the form already lives inside a framework with its own tooling.

How do I validate a field that depends on another, like a password confirmation?

Use setCustomValidity() on the second field, triggered by input on both fields, and re-check the second one whenever the first changes.

Losing leads because your forms explain errors badly? We build clear, accessible forms with validation from browser to server.

Partager LinkedIn Facebook X WhatsApp
</>

webtestudio

Agence web : sites WordPress sur mesure, thèmes premium et logiciels SaaS.

Parler de votre projet →