Skip to curriculum
Jump to the editor

24.4. A schema validator

Medium
Topics

This question is in

24. Build a small library
30–45 min

Data that comes from outside your code, such as a form, an API response or localStorage, can be anything. A schema validator describes the shape you expect once, then checks any value against it and says exactly what is wrong, field by field. Forms use the errors to show a message next to each input; API layers use them to refuse bad data before it spreads.

Write a small validator in schema.js: an object v whose functions create schemas, chainable rules, and a validate method.

Signature

JAVASCRIPT
const v = {
  string(),       // schema for strings
  number(),       // schema for numbers
  boolean(),      // schema for booleans
  object(shape),  // shape: { key: schema, … }
};

schema.optional()          // every schema
schema.min(n), schema.max(n) // string and number schemas
schema.integer()           // number schemas
schema.validate(value)
// { ok: true, value }  or  { ok: false, errors: [{ path, message }] }

path is "" for the value itself and the field's key for a field of an object.

Requirements

  1. v.string() accepts only strings, v.number() only numbers other than NaN, v.boolean() only true and false. Nothing is converted. The messages are Expected a string, Expected a number and Expected a boolean.
  2. A valid result is { ok: true, value } with no errors key; an invalid one is { ok: false, errors } with no value key.
  3. undefined fails with Required, unless the schema is optional: then it passes as { ok: true, value: undefined }. An optional schema still checks any other value, null included.
  4. For strings, min(n) and max(n) limit the length: Must be at least <n> characters, Must be at most <n> characters. For numbers, they limit the value: Must be at least <n>, Must be at most <n>. The limits themselves are allowed.
  5. integer() fails for any number that is not an integer (Infinity included) with Must be an integer.
  6. The type is checked first. Then the rules run in the order they were chained, and the first rule that fails is the value's only error.
  7. Every method returns a new schema. The schema it was called on does not change, and the new one keeps its rules and its optional setting, whatever the order of the calls.
  8. v.object(shape) accepts a non-null object that is not an array (Expected an object otherwise). It validates every field of the shape, in the shape's order, and returns all their errors, each with the field's key as path.
  9. A key of the value that is not in the shape is an error Unknown key, reported after the field errors, in the value's key order.
  10. A valid object's value is a new object with the checked fields, each an own data property (a field named "__proto__" included; the prototype of value stays Object.prototype). Fields are read from the value's own keys: a key it only inherits counts as missing. A missing optional field is left out of it (no key with undefined). validate never changes its input.
  11. min and max with a limit that is not a finite number throw a TypeError with the message min expects a finite number (or max …).
  12. v.object throws a TypeError when the shape is not an object (v.object expects an object of schemas) or when a field is not a schema (Field "<key>" is not a schema).

Examples

JAVASCRIPT
const user = v.object({
  name: v.string().min(2),
  age: v.number().integer().min(0),
  nickname: v.string().optional(),
});

user.validate({ name: "Ada", age: 36 });
// { ok: true, value: { name: "Ada", age: 36 } }

user.validate({ name: "A", age: 3.5, role: "admin" });
// { ok: false, errors: [
//   { path: "name", message: "Must be at least 2 characters" },
//   { path: "age", message: "Must be an integer" },
//   { path: "role", message: "Unknown key" } ] }
JAVASCRIPT
const base = v.string();
const short = base.max(3);
base.validate("a long name"); // { ok: true, value: "a long name" }: base has no max
short.validate("a long name");
// { ok: false, errors: [{ path: "", message: "Must be at most 3 characters" }] }
JAVASCRIPT
v.number().validate(NaN);  // { ok: false, errors: [{ path: "", message: "Expected a number" }] }
v.number().min("5");       // throws TypeError: min expects a finite number

Environment

  • Plain JavaScript in a browser page; the tests call the global v from schema.js.
  • Objects inside objects, arrays, custom messages and custom rules are out of scope (problem 24.5 adds them). Fields are strings, numbers and booleans.
  • Any library is out of scope: write it yourself.

Hints

  1. Where does a schema keep its rules so that chaining one more rule cannot change a schema that already exists?
  2. A number's min and a string's min check different things. How can each kind of schema get its own min, while optional and validate are shared?

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…