Emmanuel Akinfulubi

JavaScriptFundamental (ES6), part 1

Build a schema validator in JavaScript

119 a schema validator built from small predicates

hard

Build a validator out of composable pieces: str, int, oneOf, optional, arrayOf and shape. Each one takes a value and returns an array of errors — empty means valid — so nesting them is just flatMap. Every error must carry a dotted path such as goods.1.kobo, and one call must report all of them.

Stuck? Three hints, smallest first
  1. 1. Make the contract "returns an array of errors". Then combining validators is concatenating arrays, which flatMap does for you.
  2. 2. shape walks Object.entries(fields), runs each rule on value[key], and prefixes the paths that come back with key.
  3. 3. optional(rule) is one line: v === undefined ? [] : rule(v). Every other rule can then assume the value is present.

The answer

const at = (path, message) => ({ path, message });
const prefix = (head, errors) =>
  errors.map((e) => ({ ...e, path: e.path ? `${head}.${e.path}` : head }));

const str = ({ min = 0 } = {}) => (v) =>
  typeof v !== 'string' ? [at('', 'must be a string')]
    : v.length < min ? [at('', `must be at least ${min} characters`)]
      : [];

const int = ({ min = -Infinity } = {}) => (v) =>
  !Number.isInteger(v) ? [at('', 'must be a whole number')]
    : v < min ? [at('', `must be at least ${min}`)]
      : [];

const oneOf = (allowed) => (v) =>
  allowed.includes(v) ? [] : [at('', `must be one of ${allowed.join(', ')}`)];

const optional = (rule) => (v) => (v === undefined ? [] : rule(v));

const arrayOf = (rule) => (v) =>
  !Array.isArray(v)
    ? [at('', 'must be an array')]
    : v.flatMap((item, i) => prefix(String(i), rule(item)));

const shape = (fields) => (v) =>
  v === null || typeof v !== 'object'
    ? [at('', 'must be an object')]
    : Object.entries(fields).flatMap(([key, rule]) => prefix(key, rule(v[key])));

const validator = (rule) => (v) => {
  const errors = rule(v);
  return errors.length ? { ok: false, errors } : { ok: true, value: v };
};

const checkVendor = validator(shape({
  name: str({ min: 3 }),
  lga: oneOf(['Eti-Osa', 'Ikeja', 'Surulere']),
  stall: optional(str({ min: 1 })),
  goods: arrayOf(shape({ item: str({ min: 2 }), kobo: int({ min: 1 }) })),
}));

const goodVendor = { name: 'Mama Nkechi', lga: 'Ikeja', goods: [{ item: 'Ugu', kobo: 50000 }] };
const badVendor = { name: 'Yo', lga: 'Ajah', goods: [{ item: 'Ugu', kobo: 0 }, { item: 7, kobo: 1.5 }] };

const bad = checkVendor(badVendor);
const paths = bad.errors.map((e) => e.path);

console.log('good :', checkVendor(goodVendor));
console.log('paths:', paths);
console.log('first:', bad.errors[0]);

Output


      
8 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 8 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

8 checks

test('a vendor that fits the schema passes and hands back the value', [checkVendor(goodVendor).ok, checkVendor(goodVendor).value.lga], [true, 'Ikeja']);
test('a bad one reports every problem, addressed by path', paths, ['name', 'lga', 'goods.0.kobo', 'goods.1.item', 'goods.1.kobo']);
test('the messages come from whichever small rule failed', bad.errors[1].message, 'must be one of Eti-Osa, Ikeja, Surulere');
test('a missing optional field is silent', checkVendor({ name: 'Baba Ali', lga: 'Ikeja', goods: [] }).ok, true);
test('but a present one is checked like any other', checkVendor({ name: 'Baba Ali', lga: 'Ikeja', stall: 9, goods: [] }).errors, [{ path: 'stall', message: 'must be a string' }]);
test('arrayOf on something that is not an array says so once', checkVendor({ name: 'Baba Ali', lga: 'Ikeja', goods: 'none' }).errors, [{ path: 'goods', message: 'must be an array' }]);
test('the top level reports an empty path, since there is nothing to name', checkVendor(null).errors, [{ path: '', message: 'must be an object' }]);
test('and any rule still works on its own, outside a schema', [str({ min: 3 })('Ojo'), int({ min: 1 })(0).length], [[], 1]);

The whole design rests on one decision: a validator returns errors, not a boolean. Booleans do not compose — two of them give you no way to say which field, at which index, failed why. An array of { path, message } concatenates, and concatenation is what flatMap is for, so shape and arrayOf are three lines each and nest to any depth without extra machinery.

prefix is the only fiddly part, and only because of the empty path at the leaves. A leaf rule does not know its own name, so it reports path: '' and each enclosing combinator prepends the key or index as the error travels outward. That is how goods.1.kobo gets built without any rule knowing where it sits.

Each rule is a factory — str({ min: 3 }) returns the validator — which is what lets the schema read like a description of the data. The last assertion is the payoff: nothing about a rule depends on the schema, so it can be tested, reused and combined on its own.

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.