Emmanuel Akinfulubi

JavaScriptFundamental (ES6), part 1

Collect all form validation errors in JavaScript

118 collect every validation error, do not throw on the first

fair

Validate a delivery form against a list of rules and return all the failures at once, as { ok: false, errors: [{ field, message }] }. Write the throwing version beside it and show that it can only ever report one problem. Then show that the order of the rules changes the order of the report but not the set of failures.

Stuck? Three hints, smallest first
  1. 1. A rule is data: a field name, a message and a predicate. Then validation is filter then map.
  2. 2. errors.length === 0 is the success test. Returning { ok: true, value } keeps callers from having to guess.
  3. 3. The eager version needs throw inside a loop, so the second failing rule never runs.

The answer

const STATES = new Set(['Lagos', 'Kano', 'Rivers', 'Enugu', 'FCT']);

const rules = [
  ['name', 'name is required', (f) => typeof f.name === 'string' && f.name.trim() !== ''],
  ['phone', 'phone must be 11 digits starting with 0', (f) => /^0\d{10}$/.test(f.phone ?? '')],
  ['state', 'state is not on the list', (f) => STATES.has(f.state)],
  ['age', 'age must be a whole number, 18 or more', (f) => Number.isInteger(f.age) && f.age >= 18],
  ['email', 'email needs exactly one @', (f) => (f.email ?? '').split('@').length === 2],
];

const check = (form) => {
  const errors = rules
    .filter(([, , ok]) => !ok(form))
    .map(([field, message]) => ({ field, message }));
  return errors.length === 0 ? { ok: true, value: form } : { ok: false, errors };
};

const firstFailureOnly = (form) => {
  try {
    for (const [field, message, ok] of rules) {
      if (!ok(form)) throw new Error(`${field}: ${message}`);
    }
    return { ok: true };
  } catch (e) {
    return { ok: false, message: e.message };
  }
};

const good = { name: 'Ngozi Okafor', phone: '08031234567', state: 'Enugu', age: 31, email: 'ngozi@example.ng' };
const wrong = { name: '   ', phone: '8031234567', state: 'Lagos Island', age: 17, email: 'ngozi.example.ng' };
const nearly = { name: 'Musa Bello', phone: '07098765432', state: 'Kano', age: 16, email: 'musa@example.ng' };

const passed = check(good);
const failed = check(wrong);
const fields = failed.errors.map((e) => e.field);
const byField = failed.errors.reduce((acc, e) => ({ ...acc, [e.field]: e.message }), {});
const eager = firstFailureOnly(wrong);
const reversedFields = [...rules].reverse().filter(([, , ok]) => !ok(wrong)).map(([f]) => f);

console.log('passed :', passed);
console.log('failed :', fields);
console.log('eager  :', eager.message);
console.log('byField:', byField);

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.

9 checks

test('a form that satisfies every rule comes back with its value', [passed.ok, passed.value.name], [true, 'Ngozi Okafor']);
test('and carries no errors key at all', 'errors' in passed, false);
test('a bad form reports every failure in one pass', [failed.ok, failed.errors.length], [false, 5]);
test('in the order the rules were declared', fields, ['name', 'phone', 'state', 'age', 'email']);
test('which reduces neatly into a lookup for a form UI', byField.age, 'age must be a whole number, 18 or more');
test('the throwing version can only ever tell you about the first', eager.message, 'name: name is required');
test('one bad field means one error, not a wall of them', check(nearly).errors.map((e) => e.field), ['age']);
test('rule order changes the report order, not which rules failed', [...reversedFields].reverse(), fields);
test('and an empty object fails all five', check({}).errors.length, 5);

Throwing on the first bad field is the wrong shape for a form. The user fixes one thing, submits, and is told about the next — five round trips for five mistakes. Collecting is barely more code: filter the rules that failed, map them to a report, and let errors.length decide the verdict.

Making a rule data rather than a line of code is what buys the rest. The rules can be reordered, filtered by field, counted, or serialised to the client, and the assertion about reversal proves the important property: the collector is order-insensitive about what it finds. Notice that f.phone ?? '' keeps a missing field from crashing the predicate — a validator that throws on absent input is not a validator.

Keep the two success shapes distinguishable. { ok: true, value } and { ok: false, errors } mean a caller writes if (!result.ok) and can never accidentally read a half-valid value, which is exactly the mistake a bare errors array invites.

Newsletter

New writing, when it lands.

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