transform
Transforms the result of a schema and can change its type. The function runs only if validation passed.
Signature
ts
function transform<T, U>(schema: Schema<T>, fn: (value: T) => U): Schema<U>Parameters
| Parameter | Type | Description |
|---|---|---|
schema | Schema<T> | The schema whose result is transformed |
fn | (value: T) => U | The transform function |
Difference from transforms in pipe
trim, toLowerCase and other actions in pipe keep the type. transform changes it: a string can become an array, a number, an object.
An exception inside fn is not turned into a validation error, it is rethrown. Validate the value with rules first, then transform it.
Examples
Comma-separated string to array
ts
const ids = transform(pipe(string(), pattern(/^\d+(,\d+)*$/)), (s) => s.split(',').map(Number));
validate(ids, '1,2,3').data; // [1, 2, 3]Dollars to cents
ts
const price = transform(pipe(coerce.number(), min(0)), (usd) => Math.round(usd * 100));See also
- preprocess — prepare the input before validation
- pipe