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
| Parameter | Type | Description |
|---|---|---|
fn | (value: unknown) => unknown | The preparation function. Receives the raw value of any type |
schema | Schema<T> | The schema that validates the result of fn |
Notes
fnreceives unvalidated data: it can be anything.- All
coercefunctions are built onpreprocess.
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.5JSON in a string
ts
const settings = preprocess(
(v) => (typeof v === 'string' ? JSON.parse(v) : v),
object({ theme: oneOf(['light', 'dark']) }),
);