Skip to content

pipe ​

为 Schema 添加规则和转换。它们在类型检查之后按顺序执行。

签名 ​

ts
function pipe<T>(schema: Schema<T>, ...actions: Action<T>[]): Schema<T>

参数 ​

参数类型说明
schemaSchema<T>基础 Schema:string()、number()、array(...)…
actionsAction<T>[]规则和转换

执行顺序 ​

  1. 先检查基础 Schema。如果出错,规则不会执行。
  2. 规则和转换从左到右执行。每一个都接收前一个的结果:pipe(string(), trim(), minLength(2)) 检查的是去除空格后的长度。
  3. 遇到第一个错误时停止。使用 validate 的 { all: true } 选项可以检查所有规则。
  4. 异步规则(checkAsync)最后执行,并且只在其他规则通过后执行。

可以传入什么 ​

类别操作
长度minLength、maxLength、length
数字min、max、between、integer
格式pattern、email、url、uuid、startsWith、endsWith、includes
日期minDate、maxDate、after、before
数组unique
校验位inn、snils、luhn
比较sameAs
转换trim、toLowerCase、toUpperCase
自定义check、checkAsync

TypeScript 会检查规则是否与 Schema 类型匹配:pipe(string(), min(1)) 会产生编译错误。

pipe 中的转换不会改变类型。要得到其他类型的值,请使用 transform。

示例 ​

用户名 ​

ts
const username = pipe(
  string(),
  trim(),
  toLowerCase(),
  minLength(3),
  maxLength(20),
  pattern(/^[a-z0-9_]+$/, '只能包含拉丁字母、数字和 _'),
);

与 optional 一起使用 ​

ts
// optional 放在 pipe 外层
const phone = optional(pipe(string(), pattern(/^1\d{10}$/)));

另请参阅 ​