Skip to content

preprocess ​

Prepares the input value before validation. Handy when data comes in an inconvenient format.

Signature ​

ts
function preprocess<T>(fn: (value: unknown) => unknown, schema: Schema<T>): Schema<T>

Parameters ​

ParameterTypeDescription
fn(value: unknown) => unknownThe preparation function. Receives the raw value of any type
schemaSchema<T>The schema that validates the result of fn

Notes ​

  • fn receives unvalidated data: it can be anything.
  • All coerce functions are built on preprocess.

Examples ​

Decimal number with a comma ​

ts
const amount = preprocess(
  (v) => (typeof v === 'string' ? Number(v.replace(',', '.')) : v),
  number(),
);

validate(amount, '1,5').data; // 1.5

JSON in a string ​

ts
const settings = preprocess(
  (v) => (typeof v === 'string' ? JSON.parse(v) : v),
  object({ theme: oneOf(['light', 'dark']) }),
);

See also ​

  • coerce — built-in type coercion
  • transform — transform the result after validation