call(back)

Input Validation

Build the validation layer for a form: declarative rules per field, one error message per field — the first failing rule's — and {} when everything is valid.

validate(values, schema) -> { fieldName: message }   // only the fields with errors
schema = { title: [rules.required(), rules.minLength(3)], email: [rules.required(), rules.email()] }

rules is a set of factories returning validators (value) => message | null, with default messages the grader checks exactly. Every factory takes an optional custom message as its last argument.

FactoryDefault message
required(msg?)Required — a missing, blank, or whitespace-only value is empty
minLength(n, msg?)Must be at least {n} characters
pattern(regex, msg?)Invalid format
email(msg?)Enter a valid email
range(min, max, msg?)Must be between {min} and {max} — non-numeric input fails too

Hints

Hint 1

Each rule is a tiny function (value) => message | null. validate walks each field's rules in order and stops at the first message — one error per field, not five.

Hint 2

Write the factories to close over their parameters and default message: minLength(n, msg = ...) returns the validator; keep the messages in one place so the UI and tests agree.

Asked at