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.

JavascriptForm Validation

Code

javascriptsnippet
19 lines
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

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.