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;Report a problem with this exampleOpens a pre-filled issue on GitHub.