24.5. A schema validator with nested objects and custom messages
Topics
This question is in
24. Build a small libraryReal data is nested: a user has an address, an order has a list of items, each item has a quantity. A validator for it must walk into objects and arrays, and say exactly where each problem is, as a path like items → 2 → qty, so a form can put the message next to the right input. And the default messages are rarely what the product wants to show, so every check needs a way to replace its text, or to compute it from the value.
Write a validator for nested data in schema.js: an object v whose functions create schemas, chainable rules with custom messages, custom checks with refine, and a validate method.
Signature
const v = {
string(message), number(message), boolean(message), // message: optional, for the type error
object(shape, message), // shape: { key: schema, … }
array(item, message), // item: the schema of every item
};
schema.min(n, message), schema.max(n, message) // strings, numbers, arrays
schema.integer(message) // numbers
schema.optional() // every schema
schema.refine(check, message) // every schema; check(value) returns true when valid
schema.validate(value)
// { ok: true, value } or { ok: false, errors: [{ path, message }] }pathis an array of object keys (strings) and array indexes (numbers):[]for the value itself,["items", 2, "qty"]deep inside.- A
messageis optional everywhere. It is a string, or a function that receives{ value, path, limit }and returns the text.limitis the number given tominormax, andundefinedfor every other check.
Requirements
- Types: strings, numbers other than
NaN, booleans, non-null non-array objects, and arrays (Array.isArray). Nothing is converted. Default messages:Expected a string,Expected a number,Expected a boolean,Expected an object,Expected an array. undefined(an array hole too) fails withRequiredunless the schema is optional. This message is fixed.nullis a value, not a missing one.- Rules and their default messages: strings,
Must be at least <n> charactersandMust be at most <n> characters; numbers,Must be at least <n>,Must be at most <n>andMust be an integer; arrays,Must have at least <n> itemsandMust have at most <n> items. The limits themselves pass. - Order at one level: missing value, then type (on failure, that is the only error and nothing inside is checked), then the rules in chaining order (the first that fails gives one error), then the children: every field of an object in the shape's order, or every item of an array in index order. The value's own error comes before its children's errors, and both are reported.
- An object reports each key of the value that is not in the shape as
Unknown key, at that key's path, after its fields. - All errors from every depth are returned, in that order, each with its full path.
- A valid result's
valueis a new copy at every level: new objects and new arrays, built from the checked values. A missing optional field is left out of an object; anundefinedoptional item stays in its place in an array. Each field of a copy is an own data property, a field named"__proto__"included (the copy's prototype staysObject.prototype), and fields are read from the input's own keys: a key it only inherits counts as missing.validatenever changes its input. - A message given to
v.string(message)(and the other factories) replaces the type error's text. A message given to a rule replaces that rule's text. refine(check, message)adds a custom check. It runs only when everything else at this level and below passed, receives the new checked value, and fails whencheckreturns a false value, with the message (defaultInvalid value) at the schema's own path. Several refinements run in chaining order and stop at the first failure.- Every method returns a new schema; the original never changes, and the copy keeps every other setting.
- These throw a
TypeErrorwhen the schema is built:v.arraywithout a schema (v.array expects a schema),v.objectwith a shape that is not an object (v.object expects an object of schemas) or with a field that is not a schema (Field "<key>" is not a schema),refinewithout a function (refine expects a function),minormaxwithout a finite number (min expects a finite number), and a message that is neither a string nor a function (message must be a string or a function).
Examples
const order = v.object({
email: v.string("Enter your email"),
items: v.array(v.object({
sku: v.string(),
qty: v.number().integer().min(1, ({ limit }) => `Order at least ${limit}`),
})).min(1, "Add an item"),
});
order.validate({ email: 42, items: [{ sku: "A1", qty: 2 }, { qty: 0 }] });
// { ok: false, errors: [
// { path: ["email"], message: "Enter your email" },
// { path: ["items", 1, "sku"], message: "Required" },
// { path: ["items", 1, "qty"], message: "Order at least 1" } ] }const signup = v.object({ password: v.string().min(8), confirm: v.string() })
.refine((value) => value.password === value.confirm, "Passwords differ");
signup.validate({ password: "secret12", confirm: "secret13" });
// { ok: false, errors: [{ path: [], message: "Passwords differ" }] }
signup.validate({ password: "short", confirm: "short" });
// { ok: false, errors: [{ path: ["password"], message: "Must be at least 8 characters" }] }
// the refinement did not run: a field had failedv.array(v.number().optional()).validate([1, undefined, 3]);
// { ok: true, value: [1, undefined, 3] }
v.array("string"); // throws TypeError: v.array expects a schemaEnvironment
- Plain JavaScript in a browser page; the tests call the global
vfromschema.js. - Data with cycles,
Map,Set,Date, unions and asynchronous checks are out of scope. Acheckpassed torefinethat throws may let the error through. - Any library is out of scope: write it yourself.
Hints
- A field deep inside does not know where it sits. What could each level pass down so the deepest check can build its path?
- The public
validatereturns{ ok, … }, but a parent needs its children's errors and values together. What would an inner method return instead? - Which methods are the same for every kind of schema, and which differ by kind?
The explanation comes with the course
A walkthrough of every line of a solution, the mistakes the tests catch, other ways to write it, and links to the lessons that teach each idea.
- Every line explained
- The mistakes each test catches
- Links to the lessons behind it