Skip to content
Backend logic · Core · about 20 minutes

Request body validation

Implement validate(schema, body). The schema maps field names to rules: type ('string', 'number' or 'boolean'), and optional required, min, max and enum. Check the fields in schema order and give each at most one error, the first that applies: 'is required' (undefined or null counts as missing; a missing optional field is fine), 'must be a <type>' (a number must be finite), 'must be at least <min>' or 'must be at most <max>' (string length, number value), 'must be one of <values joined by comma and space>'. Return { ok: false, errors: [{ field, message }] } with every error, or { ok: true, value } with only the schema fields that were given.

Start from

function validate(schema, body) {
  // Return { ok, errors } or { ok, value } for this body.
}

Hints

Each hint gives away a little more. Open one only when you need it.

  1. Hint 1

    Loop over Object.entries(schema), and write a small function that returns the first message for one field, or null.

  2. Hint 2

    Check presence first and skip the other rules when an optional field is missing.

  3. Hint 3

    Collect every error before returning, so the client can show them all at once.

Solution

The app has this lab in JavaScript, TypeScript and Python. This page shows the JavaScript code.

From here on the page gives the method away. If you are still solving, go back to the hints.

JavaScript
function validate(schema, body) {
  const errors = [];
  const value = {};
  for (const [field, rule] of Object.entries(schema)) {
    const given = body[field];
    if (given === undefined || given === null) {
      if (rule.required) errors.push({ field, message: "is required" });
      continue;
    }
    const message = problem(rule, given);
    if (message) errors.push({ field, message });
    else value[field] = given;
  }
  return errors.length ? { ok: false, errors } : { ok: true, value };
}

function problem(rule, given) {
  if (typeof given !== rule.type || (rule.type === "number" && !Number.isFinite(given)))
    return "must be a " + rule.type;
  const size = rule.type === "string" ? given.length : given;
  if (rule.min !== undefined && size < rule.min) return "must be at least " + rule.min;
  if (rule.max !== undefined && size > rule.max) return "must be at most " + rule.max;
  if (rule.enum && !rule.enum.includes(given)) return "must be one of " + rule.enum.join(", ");
  return null;
}

What an interviewer looks for

Every endpoint validates its input before touching the database. Interviewers look for all errors returned at once, unknown fields dropped, and null treated as missing.