← All Exercises
Composable Typed Form Validators
intermediatetypescript
Background
Form validation benefits from small reusable rules instead of one large conditional. A typed error union keeps messages consistent and lets the UI map each code to localized copy.
Problem
Define FieldError as a union of REQUIRED, INVALID_EMAIL, TOO_YOUNG, and INVALID_TYPE, and a Validator<T> type returning FieldError or null. Implement required, email, and minimumAge validators plus a validate(value, ...rules) helper that stops at the first error. Validate a form with email, age, and name, aggregating one error per field.
Input
A JSON object with form containing email, age, and name values.
Output
A JSON object with valid (boolean) and errors, a map containing only the first error per field.
Sample tests
Sample 1
Input: {"form":{"email":"bad","age":17,"name":""}}Expected: {"valid":false,"errors":{"email":"INVALID_EMAIL","age":"TOO_YOUNG","name":"REQUIRED"}}Sample 2
Input: {"form":{"email":"[email protected]","age":36,"name":"Ada"}}Expected: {"valid":true,"errors":{}}Sample 3
Input: {"form":{"email":"[email protected]","age":"x","name":"Ada"}}Expected: {"valid":false,"errors":{"age":"INVALID_TYPE"}}Your solution
Learning objective
Design small typed validators, compose them, and produce deterministic error maps.