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.
Code
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
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.Credit Card Brand DetectorIdentify the card network from a number's prefix and length, validate the Luhn checksum, and show a masked form and the issuer identification number.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.