JavaScriptFundamental (ES6), part 2
Validation library with error paths in JavaScript
118 Validation that reports every problem, with the path to each
hardFinish the set by building a validation library out of nothing but functions. A validator takes a value and a path and returns either { ok: true, value } or { ok: false, errors: [{ path, message }] }. Write the leaves — string, whole number, one-of — and the combinators that build structures out of them: all for chaining rules on one field, optional, arrayOf and shape. The point is the reporting: one bad request must come back with every problem in it, each carrying a path like items[1].kobo, so a form can highlight all of its fields at once. Then be deliberate about where you accumulate and where you stop.
Stuck? Three hints, smallest first
- 1. A validator is just
(value, path) => result. Every combinator takes validators and returns one, so nothing needs a class or a registry. - 2.
shapeandarrayOfcollect errors from every field and every element before returning.allis the opposite: it stops at the first failure, because a length check on a value that is not a string is meaningless. - 3. Build the path as you descend:
path + '.' + keyfor a field,path + '[' + index + ']'for an element. Pass it down, never reconstruct it on the way back up.
const kindOf = (v) => (v === null ? 'null' : Array.isArray(v) ? 'array' : typeof v);
const pass = (value) => ({ ok: true, value });
const failAt = (path, message) => ({ ok: false, errors: [{ path, message }] });
const isString = () => (value, path) =>
typeof value === 'string' ? pass(value) : failAt(path, 'expected a string, got ' + kindOf(value));
const isWholeNumber = () => (value, path) =>
Number.isInteger(value) ? pass(value) : failAt(path, 'expected a whole number, got ' + kindOf(value));
const atLeast = (n) => (value, path) =>
value >= n ? pass(value) : failAt(path, 'must be at least ' + n);
const longerThan = (n) => (value, path) =>
value.length > n ? pass(value) : failAt(path, 'must be longer than ' + n + ' characters');
const oneOf = (allowed) => (value, path) =>
allowed.indexOf(value) !== -1 ? pass(value) : failAt(path, 'must be one of ' + allowed.join(', '));
// Chaining STOPS at the first failure: later rules assume the earlier ones held.
const all = (...checks) => (value, path) => {
let current = value;
for (const check of checks) {
const result = check(current, path);
if (!result.ok) return result;
current = result.value;
}
return pass(current);
};
const optional = (check) => (value, path) => (value === undefined ? pass(undefined) : check(value, path));
// Structures ACCUMULATE: every element is checked before anything is returned.
const arrayOf = (check) => (value, path) => {
if (!Array.isArray(value)) return failAt(path, 'expected an array, got ' + kindOf(value));
const out = [];
const errors = [];
value.forEach((item, index) => {
const result = check(item, path + '[' + index + ']');
if (result.ok) out.push(result.value);
else for (const e of result.errors) errors.push(e);
});
return errors.length ? { ok: false, errors } : pass(out);
};
const shape = (fields, { allowUnknown = false } = {}) => (value, path) => {
if (value === null || typeof value !== 'object' || Array.isArray(value)) {
return failAt(path, 'expected an object, got ' + kindOf(value));
}
const out = {};
const errors = [];
for (const key of Object.keys(fields)) {
const at = path ? path + '.' + key : key;
const result = fields[key](value[key], at);
if (!result.ok) { for (const e of result.errors) errors.push(e); continue; }
if (result.value !== undefined) out[key] = result.value;
}
if (!allowUnknown) {
for (const key of Object.keys(value)) {
if (!Object.prototype.hasOwnProperty.call(fields, key)) {
errors.push({ path: path ? path + '.' + key : key, message: 'unknown key' });
}
}
}
return errors.length ? { ok: false, errors } : pass(out);
};
const lineItem = shape({
sku: all(isString(), longerThan(2)),
kobo: all(isWholeNumber(), atLeast(1)),
});
const order = shape({
till: all(isString(), longerThan(2)),
currency: oneOf(['NGN', 'USD']),
note: optional(all(isString(), longerThan(0))),
items: arrayOf(lineItem),
});
const report = (result) => (result.ok ? 'ok' : result.errors.map((e) => e.path + ': ' + e.message));
const good = order({
till: 'Balogun 1',
currency: 'NGN',
items: [{ sku: 'ADR-1', kobo: 450000 }, { sku: 'ADR-2', kobo: 125000 }],
}, '');
const goodStory = [good.ok, good.value, 'note' in good.value];
const messy = order({
till: 'B',
currency: 'GBP',
items: [{ sku: 'ADR-1', kobo: 4.5 }, { kobo: 0 }, 'not an object'],
discount: 500,
}, '');
const everyProblem = report(messy);
const chainStops = report(order({ till: 42, currency: 'NGN', items: [] }, ''));
const optionalStory = [
report(order({ till: 'Ikeja 1', currency: 'NGN', note: 'rush', items: [] }, '')),
report(order({ till: 'Ikeja 1', currency: 'NGN', note: '', items: [] }, '')),
report(order({ till: 'Ikeja 1', currency: 'NGN', note: 7, items: [] }, '')),
];
const unknownKeys = [
report(order({ till: 'Ikeja 1', currency: 'NGN', items: [], extra: 1 }, '')),
report(shape({ till: isString() }, { allowUnknown: true })({ till: 'Ikeja 1', extra: 1 }, '')),
];
const notAnArray = report(order({ till: 'Ikeja 1', currency: 'NGN', items: { 0: 'x' } }, ''));
const nullVsMissing = [
report(order({ till: null, currency: 'NGN', items: [] }, '')),
report(order({ currency: 'NGN', items: [] }, '')),
];
// A new rule is just another function. Nothing above it changes.
const divisibleBy = (n) => (value, path) =>
value % n === 0 ? pass(value) : failAt(path, 'must be a multiple of ' + n);
const roundKobo = shape({ kobo: all(isWholeNumber(), atLeast(1), divisibleBy(50)) });
const customRule = [report(roundKobo({ kobo: 450000 }, '')), report(roundKobo({ kobo: 12 }, ''))];
const deep = shape({ batches: arrayOf(shape({ items: arrayOf(lineItem) })) });
const deepReport = report(deep({
batches: [
{ items: [{ sku: 'ADR-1', kobo: 100 }] },
{ items: [{ sku: 'ADR-2', kobo: 100 }, { sku: 'X', kobo: 100 }] },
],
}, ''));
console.log('good order :', goodStory);
console.log('every problem:', everyProblem);
console.log('deep path :', deepReport);
Output
9 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 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('a valid order passes and hands back the value it validated', goodStory, [true, { till: 'Balogun 1', currency: 'NGN', items: [{ sku: 'ADR-1', kobo: 450000 }, { sku: 'ADR-2', kobo: 125000 }] }, false]);
test('one bad order reports every problem at once, each with a path into the structure', everyProblem, ['till: must be longer than 2 characters', 'currency: must be one of NGN, USD', 'items[0].kobo: expected a whole number, got number', 'items[1].sku: expected a string, got undefined', 'items[1].kobo: must be at least 1', 'items[2]: expected an object, got string', 'discount: unknown key']);
test('within one field the chain stops at the first failure: one message, not two', chainStops, ['till: expected a string, got number']);
test('an optional field may be absent, but not present and wrong', optionalStory, ['ok', ['note: must be longer than 0 characters'], ['note: expected a string, got number']]);
test('an unknown key is reported at its own path unless the shape allows it', unknownKeys, [['extra: unknown key'], 'ok']);
test('an object where an array belongs is reported once, without being indexed', notAnArray, ['items: expected an array, got object']);
test('null is a value that fails its check, while missing reports the type it lacked', nullVsMissing, [['till: expected a string, got null'], ['till: expected a string, got undefined']]);
test('a brand new rule composes into the existing chain with nothing else changed', customRule, ['ok', ['kobo: must be a multiple of 50']]);
test('and a path is built on the way down, so three levels deep still reads plainly', deepReport, ['batches[1].items[1].sku: must be longer than 2 characters']);
This is combinator design, and the whole library is functions returning functions. There is no base class, no schema object and no registry, because a validator is nothing but (value, path) => result — so arrayOf(shape({ ... })) composes for the same reason map and filter compose. The eighth assertion is the payoff: divisibleBy is four lines written outside the library and it drops into an existing chain with nothing above it modified. That is the test of whether an abstraction is actually open.
The second and third assertions are two opposite decisions, and getting them the wrong way round is what makes validation libraries annoying. shape and arrayOf accumulate: a form that highlights one field, waits for a fix, then highlights the next is a bad form, so every field and every element is checked before anything is returned. all short-circuits: once till is known not to be a string, running a length check on it would either crash or produce a second message about a problem the user does not have. Accumulate across siblings, stop within a chain.
The path is the other half of a usable error, and it only works if it is built on the way down. Each combinator appends its own segment before recursing — '.' + key for a field, '[' + index + ']' for an element — so a leaf that fails already knows its full address and returns batches[1].items[1].sku without anything reassembling it on the way back. Try to reconstruct the path while unwinding and every combinator has to know about every other one.
Two distinctions the assertions pin down because they are easy to blur. null is a value and fails its check, while a missing key arrives as undefined and is reported as such — the messages differ, and a user needs them to. And an unknown key is a failure by default rather than a silent drop: an API that ignores discont because it expected discount takes the money and applies nothing, which is the kind of bug that is only ever found by a customer.