pipe
Adds rules and transforms to a schema. They run in order after the type check.
Signature
ts
function pipe<T>(schema: Schema<T>, ...actions: Action<T>[]): Schema<T>Parameters
| Parameter | Type | Description |
|---|---|---|
schema | Schema<T> | The base schema: string(), number(), array(...)… |
actions | Action<T>[] | Rules and transforms |
Execution order
- The base schema is checked. On error the rules don't run.
- Rules and transforms run left to right. Each one gets the result of the previous:
pipe(string(), trim(), minLength(2))checks the length of the trimmed string. - Execution stops at the first error. With the
{ all: true }option ofvalidateall rules are checked. - Async rules (
checkAsync) run last and only if the others passed.
What you can pass
| Kind | Actions |
|---|---|
| Length | minLength, maxLength, length |
| Numbers | min, max, between, integer |
| Format | pattern, email, url, uuid, startsWith, endsWith, includes |
| Dates | minDate, maxDate, after, before |
| Arrays | unique |
| Checksums | inn, snils, luhn |
| Comparison | sameAs |
| Transforms | trim, toLowerCase, toUpperCase |
| Custom | check, checkAsync |
TypeScript checks that a rule matches the schema type: pipe(string(), min(1)) is a compile error.
Transforms inside pipe keep the type. To get a value of another type, use transform.
Examples
Username
ts
const username = pipe(
string(),
trim(),
toLowerCase(),
minLength(3),
maxLength(20),
pattern(/^[a-z0-9_]+$/, 'Only latin letters, digits and _'),
);With optional
ts
// optional goes outside pipe
const phone = optional(pipe(string(), pattern(/^\+1\d{10}$/)));