Skip to content
jshacks.dev
Functions

How to Validate Function Arguments Without a Library

Validate JavaScript function arguments without a library using typeof checks, assertion helpers, clear error messages and a small schema checker. Node.js 24.

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

A function that receives the wrong argument usually fails later and somewhere else. Pass "5" where a number belongs and "5" + 1 becomes "51", a bug that surfaces three calls away in a total that looks slightly wrong. Pass undefined and the failure is Cannot read properties of undefined, which says nothing about which argument was missing. Validation at the boundary turns those vague downstream failures into one clear error at the call that caused them. Libraries such as Zod and Joi do this well, and for a small function or a small project a few hand-written checks are enough and add no dependency. This post builds them on Node.js 24: the basic type checks, small assertion helpers, good error messages, an options-object checker and a tiny schema validator, and says where a library becomes the better choice. For the options pattern the checks usually protect, see writing a function that accepts an options object with defaults.

Check at the boundary

Validate where outside data enters your code: public functions, request handlers, module exports. Do not repeat checks in private helpers that only your own code calls, since that is noise and costs time. The question to ask is "who can call this with something I did not expect", and the answer is usually "anyone outside this module".

The simplest check is a typeof test and a throw.

JavaScript
function area(width, height) {
  if (typeof width !== "number" || typeof height !== "number") {
    throw new TypeError("width and height must be numbers");
  }

  return width * height;
}

console.log(area(3, 4));

try {
  area("3", 4);
} catch (error) {
  console.log(error.name, error.message);
}
Text
12
TypeError width and height must be numbers

TypeError is the right class for a value of the wrong type, and RangeError for a value of the right type outside its allowed range. Using the standard classes lets callers handle them with instanceof, and matches how the language itself behaves.

That check has two gaps. It does not say which argument was wrong, and typeof NaN is "number", so area(NaN, 4) passes and returns NaN.

Better checks for numbers

A number argument usually means a finite number, and often an integer or a positive one. Name the checks.

JavaScript
const isFiniteNumber = (v) => typeof v === "number" && Number.isFinite(v);

function assertNumber(name, value, { min = -Infinity, max = Infinity, integer = false } = {}) {
  if (!isFiniteNumber(value)) {
    throw new TypeError(`${name} must be a finite number, got ${describe(value)}`);
  }

  if (integer && !Number.isInteger(value)) {
    throw new TypeError(`${name} must be an integer, got ${value}`);
  }

  if (value < min || value > max) {
    throw new RangeError(`${name} must be between ${min} and ${max}, got ${value}`);
  }

  return value;
}

function describe(value) {
  if (value === null) return "null";
  if (Array.isArray(value)) return "an array";
  return typeof value === "string" ? JSON.stringify(value) : String(value);
}

for (const bad of ["3", NaN, 2.5, 200, null]) {
  try {
    assertNumber("percent", bad, { min: 0, max: 100, integer: true });
  } catch (error) {
    console.log(error.name + ": " + error.message);
  }
}
Text
TypeError: percent must be a finite number, got "3"
TypeError: percent must be a finite number, got NaN
TypeError: percent must be an integer, got 2.5
RangeError: percent must be between 0 and 100, got 200
TypeError: percent must be a finite number, got null

Each message names the parameter and shows the offending value. Quoting strings with JSON.stringify makes "3" visibly different from the number 3, which is exactly the confusion that causes this class of bug. The helper returns the validated value, so it can be used inline: const p = assertNumber("percent", input, { min: 0, max: 100 }).

Strings, arrays and enums

The same shape works for other types. Strings often need a non-empty rule, arrays need an element check and enumerated values need to say which values are allowed.

JavaScript
function assertString(name, value, { nonEmpty = false, pattern } = {}) {
  if (typeof value !== "string") {
    throw new TypeError(`${name} must be a string, got ${describe(value)}`);
  }

  if (nonEmpty && value.trim() === "") {
    throw new RangeError(`${name} must not be empty`);
  }

  if (pattern && !pattern.test(value)) {
    throw new RangeError(`${name} has an invalid format: ${JSON.stringify(value)}`);
  }

  return value;
}

function assertOneOf(name, value, allowed) {
  if (!allowed.includes(value)) {
    throw new RangeError(`${name} must be one of ${allowed.join(", ")}, got ${describe(value)}`);
  }

  return value;
}

function assertArrayOf(name, value, check) {
  if (!Array.isArray(value)) {
    throw new TypeError(`${name} must be an array, got ${describe(value)}`);
  }

  value.forEach((item, index) => check(`${name}[${index}]`, item));

  return value;
}

try {
  assertOneOf("level", "verbose", ["debug", "info", "warn"]);
} catch (error) {
  console.log(error.message);
}

try {
  assertArrayOf("ids", [1, 2, "x"], (n, v) => assertNumber(n, v, { integer: true }));
} catch (error) {
  console.log(error.message);
}

try {
  assertString("email", "not-an-email", { pattern: /^[^@\s]+@[^@\s]+$/ });
} catch (error) {
  console.log(error.message);
}
Text
level must be one of debug, info, warn, got "verbose"
ids[2] must be a finite number, got "x"
email has an invalid format: "not-an-email"

The array checker passes a name such as ids[2] to the item check, so the message points at the exact element. That detail is the difference between an error you can act on and one you have to hunt for.

A word about the email pattern: it only checks that there is something, an at sign and something else, which is all a format check can honestly promise. Whether the address exists is only known by sending mail to it.

Validating an options object

Functions with an options object need to check that object, including keys that should not be there.

JavaScript
function createServer(options = {}) {
  if (options === null || typeof options !== "object" || Array.isArray(options)) {
    throw new TypeError(`options must be an object, got ${describe(options)}`);
  }

  const known = ["port", "host", "logLevel"];
  const unknown = Object.keys(options).filter((key) => !known.includes(key));

  if (unknown.length > 0) {
    throw new TypeError(`unknown option(s): ${unknown.join(", ")}`);
  }

  const port = assertNumber("port", options.port ?? 3000, { min: 1, max: 65535, integer: true });
  const host = assertString("host", options.host ?? "localhost", { nonEmpty: true });
  const logLevel = assertOneOf("logLevel", options.logLevel ?? "info", ["debug", "info", "warn"]);

  return { port, host, logLevel };
}

console.log(createServer({ port: 8080 }));

try {
  createServer({ prot: 8080 });
} catch (error) {
  console.log(error.message);
}

try {
  createServer({ port: 70000 });
} catch (error) {
  console.log(error.message);
}
Text
{ port: 8080, host: 'localhost', logLevel: 'info' }
unknown option(s): prot
port must be between 1 and 65535, got 70000

Defaults are applied with ?? before validation, so a default is checked like any other value, which catches a bad default in your own code too. Rejecting unknown keys turns a misspelled prot from a silently ignored option into an immediate error.

A tiny schema validator

When several functions share the same kinds of rules, write the rules as data and validate with one function.

JavaScript
const checks = {
  number: (name, v, rule) => assertNumber(name, v, rule),
  string: (name, v, rule) => assertString(name, v, rule),
  oneOf: (name, v, rule) => assertOneOf(name, v, rule.values),
};

function validate(schema, input) {
  const output = {};

  for (const [key, rule] of Object.entries(schema)) {
    const value = input[key] ?? rule.default;

    if (value === undefined) {
      if (rule.required) throw new TypeError(`${key} is required`);
      continue;
    }

    output[key] = checks[rule.type](key, value, rule);
  }

  return output;
}

const schema = {
  name: { type: "string", required: true, nonEmpty: true },
  age: { type: "number", integer: true, min: 0 },
  role: { type: "oneOf", values: ["admin", "user"], default: "user" },
};

console.log(validate(schema, { name: "Ada", age: 36 }));

try {
  validate(schema, { age: 5 });
} catch (error) {
  console.log(error.message);
}
Text
{ name: 'Ada', age: 36, role: 'user' }
name is required

Thirty lines of rules and one loop give you required fields, defaults and typed checks, with the messages of the earlier helpers. The output contains only the keys named in the schema, so anything extra in the input is dropped, which is also a form of safety when the input comes from outside.

Writing messages people can act on

An error message is the whole user interface of a validation check, and a few habits make it useful. Say what was expected and what arrived, in that order: "must be a finite number, got "3"". Name the argument by the name the caller used, not by an internal variable. Show a short form of the offending value, and cut long strings, since a validation error that prints a megabyte of input is its own problem. And never include secrets: a password that failed a length check should be reported as too short, never echoed.

Keep the message stable too. Callers and tests match on it, and changing the wording in a minor release breaks them. If callers need to branch on the kind of failure, give the error a code property, such as ERR_INVALID_ARG, which is how Node.js marks its own errors, and let humans read the message while programs read the code.

Performance and where checks run

Validation costs a little on every call, which matters only in hot paths. A function called millions of times per second inside a tight loop should validate once at its entrance, for example when the loop starts, and not on every iteration. Public functions that are called occasionally can validate fully without any measurable effect. When in doubt, measure before removing a check, because a corrupted result in production costs far more than a few microseconds.

It is also reasonable to switch a check off in a trusted environment. Some libraries validate in development and skip the work in production builds through an environment flag. That trades safety for speed, so do it deliberately, and only for checks that guard against your own mistakes and not against outside input.

Where a library is the better choice

Hand-written checks stop paying off in three situations. When the data is deeply nested, with arrays of objects of objects, the checking code grows faster than the data. When you need the same schema for runtime checks and for TypeScript types, a library such as Zod gives you both from one definition, where hand-written checks leave you maintaining two. And when you need rich error reports, with every problem listed at once and paths into the input, writing and testing that yourself is a project of its own. The helpers here throw at the first problem, which is fine for programmer errors and weaker for form input, where users want to see all their mistakes together.

A reasonable rule is to use hand-written checks for a handful of internal and public functions, and a library at the edges where untrusted JSON enters the system.

Testing it

JavaScript
import test from "node:test";
import assert from "node:assert/strict";

test("assertNumber rejects strings and NaN", () => {
  assert.throws(() => assertNumber("n", "1"), TypeError);
  assert.throws(() => assertNumber("n", NaN), TypeError);
});

test("assertNumber enforces the range with RangeError", () => {
  assert.throws(() => assertNumber("n", 5, { max: 3 }), RangeError);
});

test("createServer applies defaults and rejects unknown keys", () => {
  assert.deepEqual(createServer(), { port: 3000, host: "localhost", logLevel: "info" });
  assert.throws(() => createServer({ nope: 1 }), /unknown option/);
});

test("error messages name the argument", () => {
  assert.throws(() => assertOneOf("mode", "x", ["a"]), /mode must be one of/);
});
Text
ℹ tests 4
ℹ pass 4
ℹ fail 0
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.