Validate a Form Against a Schema
Validate a submitted form object against field rules and collect every error at once, so users see all problems instead of one at a time.
Code
export function validateForm(values, rules) {
const errors = {};
for (const [field, rule] of Object.entries(rules)) {
const value = values[field];
for (const check of rule.checks ?? []) {
const message = check(value, values);
if (message) {
errors[field] = message;
break;
}
}
}
return { valid: Object.keys(errors).length === 0, errors };
}
export const required = (label) => (value) =>
value === undefined || value === null || value === ""
? label + " is required"
: null;What the code does
Count the functions required and validateForm as the entire surface area of Validate a Form Against a Schema.
Iteration is nested: for (const [field, rule] of Object.entries(rules)) frames the pass, for (const check of rule.checks ?? []) does the per-item step.
It builds and returns a fresh value rather than reusing its inputs.
Applying it
Entry signature: export function validateForm(values, rules)
Callers only need validateForm — everything else stays internal.
Statements that matter
return { valid: Object.keys(errors).length === 0, errors };
for (const check of rule.checks ?? []) {
const message = check(value, values);
if (message) {
errors[field] = message;
break;
}
}
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 `validateForm` modify its input?
- No. The code builds and returns a new value and leaves the arguments untouched, so it is safe to call on shared or frozen data structures.
- What does the package manager see?
- An empty dependency file. The snippet imports nothing that needs fetching. The file defines `required`, `validateForm` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.