24.4. A schema validator
Topics
This question is in
24. Build a small libraryData 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
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
v.string()accepts only strings,v.number()only numbers other thanNaN,v.boolean()onlytrueandfalse. Nothing is converted. The messages areExpected a string,Expected a numberandExpected a boolean.- A valid result is
{ ok: true, value }with noerrorskey; an invalid one is{ ok: false, errors }with novaluekey. undefinedfails withRequired, unless the schema is optional: then it passes as{ ok: true, value: undefined }. An optional schema still checks any other value,nullincluded.- For strings,
min(n)andmax(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. integer()fails for any number that is not an integer (Infinityincluded) withMust be an integer.- 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.
- 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.
v.object(shape)accepts a non-null object that is not an array (Expected an objectotherwise). It validates every field of the shape, in the shape's order, and returns all their errors, each with the field's key aspath.- 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. - A valid object's
valueis a new object with the checked fields, each an own data property (a field named"__proto__"included; the prototype ofvaluestaysObject.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 withundefined).validatenever changes its input. minandmaxwith a limit that is not a finite number throw aTypeErrorwith the messagemin expects a finite number(ormax …).v.objectthrows aTypeErrorwhen 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
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" } ] }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" }] }v.number().validate(NaN); // { ok: false, errors: [{ path: "", message: "Expected a number" }] }
v.number().min("5"); // throws TypeError: min expects a finite numberEnvironment
- Plain JavaScript in a browser page; the tests call the global
vfromschema.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
- Where does a schema keep its rules so that chaining one more rule cannot change a schema that already exists?
- A number's
minand a string'smincheck different things. How can each kind of schema get its ownmin, whileoptionalandvalidateare 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