Skip to curriculum
Jump to the editor

24.5. A schema validator with nested objects and custom messages

Hard
Topics

This question is in

24. Build a small library
50–75 min

Real 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

JAVASCRIPT
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 }] }
  • path is an array of object keys (strings) and array indexes (numbers): [] for the value itself, ["items", 2, "qty"] deep inside.
  • A message is optional everywhere. It is a string, or a function that receives { value, path, limit } and returns the text. limit is the number given to min or max, and undefined for every other check.

Requirements

  1. 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.
  2. undefined (an array hole too) fails with Required unless the schema is optional. This message is fixed. null is a value, not a missing one.
  3. Rules and their default messages: strings, Must be at least <n> characters and Must be at most <n> characters; numbers, Must be at least <n>, Must be at most <n> and Must be an integer; arrays, Must have at least <n> items and Must have at most <n> items. The limits themselves pass.
  4. 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.
  5. 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.
  6. All errors from every depth are returned, in that order, each with its full path.
  7. A valid result's value is 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; an undefined optional 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 stays Object.prototype), and fields are read from the input's own keys: a key it only inherits counts as missing. validate never changes its input.
  8. 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.
  9. 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 when check returns a false value, with the message (default Invalid value) at the schema's own path. Several refinements run in chaining order and stop at the first failure.
  10. Every method returns a new schema; the original never changes, and the copy keeps every other setting.
  11. These throw a TypeError when the schema is built: v.array without a schema (v.array expects a schema), v.object with 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), refine without a function (refine expects a function), min or max without 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

JAVASCRIPT
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" } ] }
JAVASCRIPT
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 failed
JAVASCRIPT
v.array(v.number().optional()).validate([1, undefined, 3]);
// { ok: true, value: [1, undefined, 3] }

v.array("string"); // throws TypeError: v.array expects a schema

Environment

  • Plain JavaScript in a browser page; the tests call the global v from schema.js.
  • Data with cycles, Map, Set, Date, unions and asynchronous checks are out of scope. A check passed to refine that throws may let the error through.
  • Any library is out of scope: write it yourself.

Hints

  1. A field deep inside does not know where it sits. What could each level pass down so the deepest check can build its path?
  2. The public validate returns { ok, … }, but a parent needs its children's errors and values together. What would an inner method return instead?
  3. 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
Back to the question
Loading the editor…