Reading Validation Errors
Part of the REST APIs section of Coddy's Node.js journey. Lesson 10 of 25.
A client needs to know which input to fix. When safeParse fails, result.error describes the problems. z.flattenError organizes them into two groups: fieldErrors for named fields, and formErrors for the object as a whole.
const issues = z.flattenError(result.error);
const fields = Object.keys(issues.fieldErrors);For a wrong title type, fields contains title. Object.keys returns an array of the property names. Call flattenError only on the failure branch. On success there is no error to flatten. This schema checks its listed fields. Strict object-level errors are introduced in Schemas with zod.
Object.keys(fieldErrors) gives the field names. Its sort() method puts those names in alphabetical order.
Challenge
EasyThis is a small practice project. Its setup is provided; edit only exercise.js.
On success return {"fields":[]}. On failure return the names in fieldErrors, sorted alphabetically. POST {"title":42,"done":"yes"} to /result returns {"fields":["done","title"]}. A valid title and boolean give an empty list.
The initial GET /result uses the supplied example {"title": 42, "done": "yes"}. Use POST /result with a JSON body to try other inputs.
Try it yourself
import { z } from 'zod';
const Task = z.object({ title: z.string(), done: z.boolean() });
export function exercise(body) {
return { fields: [] };
}
All lessons in REST APIs
1Resources and Verbs
Resources and URLsCreating with POST4Browsers, Versions and Config
What Is an OriginAllowing Another OriginCORSA Page That Calls the API2Validation and Errors
Validating InputPractice on your own: Express playground