Skip to main content

Validation

Runtime type guards for values arriving from outside the program — JSON bodies, query params, config files. Each one returns a TypeScript type predicate, so a check narrows the type at the call site instead of merely returning true; isNumber also rejects NaN, which typeof will happily call a number. This is a guard set, not a schema validator — for object shapes, coercion and useful error messages, reach for Zod, as the env module does.

Example

import { isDefined, isNumber, isString } from '@rtorcato/js-common/validation'

// A request body is `unknown` until something narrows it.
if (!isString(body.name) || !isNumber(body.age)) {
return reply.status(400).send('name and age required')
}
body.name.trim() // string — narrowed by the guard above

const ids = [1, undefined, 2].filter(isDefined) // number[], not (number | undefined)[]

isNumber rejects NaN, which typeof happily calls a number.

Import

import { isArray, isBoolean, isDefined } from '@rtorcato/js-common/validation'

Exports

NameSummary
isArrayChecks if a value is an array.
isBooleanChecks if a value is a boolean.
isDefinedChecks if a value is defined (not null or undefined).
isEmailChecks if a string is a valid email address (simple regex).
isNumberChecks if a value is a number (and not NaN).
isObjectChecks if a value is an object (but not null or array).
isStringCheck if a value is a string.
isUrlChecks if a string is a valid URL.

See also

  • boolean — logical operators and boolean coercion
  • emails — validate, normalize and mask email addresses
  • url — parse, validate and edit URLs and query params
  • strings — slugify, truncate, casing, emoji stripping