Skip to content
jshacks.dev
Functions

How to Compose Validators From Small Functions

Build input validation from small reusable checks that combine with all, any and field maps, and return clear error messages instead of throwing. Node.js 24.

8 min read
Summarize in AI
Flat illustration of an editor window full of code, with the JavaScript, TypeScript, Vite, Node.js and npm logos.

Validation code tends to grow into one long function with a pile of if statements, each guarding a field, and half of the rules repeated in other places. A cleaner design is to write each rule as a tiny function that checks one thing, and then combine those functions to describe a field, an object or a whole form. This post builds that design from scratch: the shape of a validator, a few primitives, combinators that join them with "all of" and "any of", an object validator that reports every error at once and a way to add rules that depend on other fields. The samples run on Node.js 24, and the code is plain JavaScript with no library.

The shape of a validator

Decide first what a validator is. The simplest useful shape is a function that takes a value and returns a list of error messages. An empty list means the value is valid.

JavaScript
const required = (value) =>
  value === undefined || value === null || value === "" ? ["is required"] : [];

const minLength = (min) => (value) =>
  typeof value === "string" && value !== "" && value.length < min
    ? [`must have at least ${min} characters`]
    : [];

console.log(required(""));
console.log(required("Ana"));
console.log(minLength(3)("ab"));
console.log(minLength(3)("abc"));
Text
[ 'is required' ]
[]
[ 'must have at least 3 characters' ]
[]

Returning an array and not throwing has two advantages. A caller can collect every problem and show them together, and a validator is an ordinary function that composes with others. minLength is a factory: it takes the limit and returns the validator, so minLength(3) is a rule you can name and reuse.

Notice that minLength passes for a missing value. A rule should check one thing, and "is there a value" belongs to required. That way an optional field with a length rule works when left blank.

More primitives

A handful of small rules covers a lot of ground.

JavaScript
const maxLength = (max) => (value) =>
  typeof value === "string" && value.length > max ? [`must have at most ${max} characters`] : [];

const matches = (pattern, message) => (value) =>
  typeof value === "string" && value !== "" && !pattern.test(value) ? [message] : [];

const isEmail = matches(/^[^\s@]+@[^\s@]+\.[^\s@]+$/, "must be a valid email address");

const between = (min, max) => (value) =>
  typeof value === "number" && (value < min || value > max)
    ? [`must be between ${min} and ${max}`]
    : [];

console.log(isEmail("[email protected]"), isEmail("ana@"));
console.log(between(18, 120)(15), between(18, 120)(30));
Text
[] [ 'must be a valid email address' ]
[ 'must be between 18 and 120' ] []

The email pattern is deliberately loose. It catches obvious typos and does not try to implement the full address grammar. The only reliable check of an email address is sending something to it. Each primitive is a few lines, has no dependencies and can be tested alone with a handful of inputs.

Combining with all and any

The power comes from combinators, functions that take validators and return a new one. The first runs several validators on the same value and joins their errors.

JavaScript
const all = (...validators) => (value) => validators.flatMap((validate) => validate(value));

const username = all(required, minLength(3), maxLength(12), matches(/^[a-z0-9_]+$/, "may only use a-z, 0-9 and _"));

console.log(username(""));
console.log(username("ab"));
console.log(username("Ana Maria Long Name"));
console.log(username("ana_01"));
Text
[ 'is required' ]
[ 'must have at least 3 characters' ]
[ 'must have at most 12 characters', 'may only use a-z, 0-9 and _' ]
[]

flatMap runs each validator and flattens the lists into one. The empty string produces one error because only required objects: the length rules and the pattern skip blank values, as designed. The long name breaks two rules and reports both.

Sometimes you want only the first problem, so the user does not see five messages about one empty field. A variant stops at the first failing validator.

JavaScript
const first = (...validators) => (value) => {
  for (const validate of validators) {
    const errors = validate(value);

    if (errors.length > 0) {
      return errors;
    }
  }

  return [];
};

const code = first(required, matches(/^\d{6}$/, "must be exactly 6 digits"));

console.log(code(""));
console.log(code("12ab"));
console.log(code("123456"));
Text
[ 'is required' ]
[ 'must be exactly 6 digits' ]
[]

Use all when every message is useful, and first when later rules only make sense once earlier ones pass. A third combinator, any, accepts a value if at least one validator passes, which is what you want for "an email or a phone number".

JavaScript
const any = (message, ...validators) => (value) =>
  validators.some((validate) => validate(value).length === 0) ? [] : [message];

const contact = any("must be an email or a phone number", isEmail, matches(/^\+?\d{8,15}$/, ""));

console.log(contact("[email protected]"));
console.log(contact("+84901234567"));
console.log(contact("hello"));
Text
[]
[]
[ 'must be an email or a phone number' ]

The combined message replaces the individual ones, because "must be a valid email" and "must be a phone number" are both misleading when either would do.

Validating an object

A form has several fields, each with its own validator. A small function takes a map from field name to validator and returns the errors keyed by field.

JavaScript
const shape = (fields) => (input) => {
  const errors = {};

  for (const [name, validate] of Object.entries(fields)) {
    const problems = validate(input?.[name]);

    if (problems.length > 0) {
      errors[name] = problems;
    }
  }

  return errors;
};

const validateSignup = shape({
  username,
  email: all(required, isEmail),
  age: between(18, 120),
});

console.log(validateSignup({ username: "ana_01", email: "[email protected]", age: 30 }));
console.log(validateSignup({ username: "A", email: "nope", age: 12 }));
Text
{}
{
  username: [ 'must have at least 3 characters', 'may only use a-z, 0-9 and _' ],
  email: [ 'must be a valid email address' ],
  age: [ 'must be between 18 and 120' ]
}

An empty object means valid, and a non-empty one maps each bad field to its messages, which is the format a form needs to show an error beside each input. The optional chain input?.[name] keeps the function from throwing when the input itself is missing. The age rule skips a missing age because between only checks numbers, so add required if age must be present.

A helper makes the result easy to use: Object.keys(errors).length === 0 is the validity check, and it can be wrapped as isValid.

Rules that depend on other fields

Some rules need the whole object: "confirm password must equal password", or "end date must be after start date". Give a validator a second argument, the full input, and the combinators pass it along.

JavaScript
const sameAs = (otherField, label) => (value, input) =>
  value !== input?.[otherField] ? [`must match ${label}`] : [];

const validateReset = (input) => {
  const errors = {};
  const pwd = all(required, minLength(8))(input.password);
  const confirm = sameAs("password", "the password")(input.confirm, input);

  if (pwd.length) errors.password = pwd;
  if (confirm.length) errors.confirm = confirm;

  return errors;
};

console.log(validateReset({ password: "s3cret-pass", confirm: "s3cret-pass" }));
console.log(validateReset({ password: "short", confirm: "other" }));
Text
{}
{
  password: [ 'must have at least 8 characters' ],
  confirm: [ 'must match the password' ]
}

The sameAs rule takes the value and the whole input. The all, first and any combinators above forward only value, so a cross-field rule inside them would not see the input. If you plan such rules from the start, make each combinator forward every argument it receives, as in (...args) => validators.flatMap((validate) => validate(...args)).

Async validators

Some checks need a database or an API: is this username taken? Make the validator return a promise and combine with Promise.all.

JavaScript
const takenNames = new Set(["admin", "root"]);

const isAvailable = async (value) => {
  await new Promise((resolve) => setTimeout(resolve, 5));
  return takenNames.has(value) ? ["is already taken"] : [];
};

const allAsync = (...validators) => async (value) =>
  (await Promise.all(validators.map(async (validate) => validate(value)))).flat();

const checkUsername = allAsync(username, isAvailable);

console.log(await checkUsername("admin"));
console.log(await checkUsername("ana_01"));
Text
[ 'is already taken' ]
[]

Wrapping each call in async (validate) => validate(value) lets one list hold both synchronous and asynchronous validators. Run the cheap synchronous rules first and skip the expensive call when they fail, with first: there is no point asking the database about a name that is empty.

Keeping messages out of the rules

Hard coded English messages limit reuse. If you need translations or different wording per form, return a code and a parameters object, and map them to text in one place.

JavaScript
const minLengthCoded = (min) => (value) =>
  typeof value === "string" && value.length < min ? [{ code: "min_length", min }] : [];

const messages = { min_length: ({ min }) => `must have at least ${min} characters` };

const render = (errors) => errors.map((error) => messages[error.code](error));

console.log(render(minLengthCoded(3)("ab")));
Text
[ 'must have at least 3 characters' ]

The rule stays the same, and the message layer can change by language. For a small app, plain strings are fine, and you can switch later because the rules are isolated.

Testing the rules

Small rules are cheap to test, and the tests double as documentation of what each rule accepts. Test each primitive with a valid value, an invalid value and the blank cases, since "does this rule skip an empty value" is the question that most often differs from what the author remembers. Test each combinator with fake validators, such as () => ["a"] and () => [], so the test covers the combining logic and not the rules inside it. Finally, keep one or two tests that run a whole form object through shape, as an integration check that the pieces fit.

A last design point: decide where blank values are handled and keep it uniform. In this design required is the only rule that complains about a blank, and every other rule passes on it. That convention makes optional fields free, because you simply leave required out. If some rules reject blanks and others accept them, you will spend your time asking why a field behaves differently from the one beside it.

When to use a library

This design covers form checks and request bodies of moderate complexity. If you need nested schemas, type inference in TypeScript, coercion of strings to numbers or a standard error format across a large API, a schema library does the same job with more features. The principle is identical: small checks, combined. Writing your own first is a good way to understand what the library is doing.

Also inPatterns
Share

Keep reading

Flat illustration of two options weighed side by side, with the JavaScript, Vite and Node.js logos.
Functions

Classes vs Factory Functions

Classes vs factory functions in JavaScript compared on private state, this, instanceof, inheritance, memory, JSON and testing, with exact output.

7 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.