← All Exercises

Validate a Payload Against a Field Schema

basicjavascript~25min

Background

Validation errors that only say "invalid payload" force clients to guess. Field-level codes are what API consumers can actually act on.

Problem

Check required fields and declared types in a request payload and return sorted error codes, including the field name in every code.

Input

JSON object: { schema: { required: string[], types: { [field]: "string"|"number"|"boolean" } }, payload: object }

Output

JSON array of "<field>:<issue>" strings, sorted

Sample tests

Sample 1

Input: {"schema":{"required":["email"],"types":{"email":"string","age":"number"}},"payload":{"age":"30"}}
Expected: ["age:expected-number","email:required"]

Sample 2

Input: {"schema":{"required":["email"],"types":{"email":"string"}},"payload":{"email":"[email protected]"}}
Expected: []

Your solution

Learning objective

Design validation errors that clients can map to the exact field.