object
包含指定字段的对象。用各自的 Schema 校验每个字段,并一次性收集所有字段的错误。
签名
ts
function object<S extends Record<string, Schema>>(shape: S, options?: ObjectOptions): Schema<ObjectOut<S>>
interface ObjectOptions {
unknown?: 'strip' | 'strict' | 'passthrough';
message?: Message;
}参数
| 参数 | 类型 | 说明 |
|---|---|---|
shape | Record<string, Schema> | 对象的字段及其 Schema |
options.unknown | 'strip' | 'strict' | 'passthrough' | 如何处理 shape 中没有的字段。默认为 strip |
options.message | Message | 值为空或不是对象时的自定义信息 |
多余字段
| 模式 | 不在 shape 中的字段会怎样 |
|---|---|
strip(默认) | 从 data 中删除。防止批量赋值:请求中的 isAdmin: true 不会进入数据库 |
strict | 每个多余字段产生一个 unknownKey 错误 |
passthrough | 原样保留在 data 中 |
错误代码
| 代码 | 触发条件 | 默认信息 |
|---|---|---|
required | 值为空 | Required |
object | 不是对象(或是数组) | Must be an object |
unknownKey | strict 模式下的多余字段 | Unknown field |
可以修改这些文本:见 错误信息与国际化。
注意事项
- 没有值的
optional字段根本不会出现在data中。 - 只读取对象自身的属性,不读取原型。输入中的
__proto__键是安全的。 - 嵌套对象的错误带有路径:
address.city。
示例
嵌套对象
ts
const Order = object({
customer: object({
name: string(),
phone: string(),
}),
address: object({
city: string(),
street: string(),
}),
});
validate(Order, { customer: { name: 'Li' }, address: {} }).errors;
// { 'customer.phone': 'Required', 'address.city': 'Required', 'address.street': 'Required' }严格的 API
ts
const UpdateUser = object({ name: optional(string()) }, { unknown: 'strict' });
validate(UpdateUser, { name: 'Li', isAdmin: true }).errors; // { isAdmin: 'Unknown field' }另请参阅
- array
- optional:选填字段
- sameAs:比较字段
- TypeScript:从 Schema 获取对象类型