问题描述
我正在创建一些 Yup 模式,例如:
let validationSchema = yup.object({
length: yup.number().min(1)
});
在声明之后有没有办法扩展它,就像我这样设置架构一样?
let validationSchema = yup.object({
length: yup.number().min(1).required(true)
});
解决方法
在 Yup 中最接近模式扩展/继承的是使用
object.shape
基于现有架构创建新架构:
Yup documentation
object.shape(fields: object,noSortEdges?: Array<[string,string]>): Schema
定义对象的键和所述键的模式。 请注意,您可以链接 shape 方法,其作用类似于对象扩展
const baseSchema = Yup.object().shape({
id: string().isRequired(),name: string().isRequired()
})
const someSchema = baseSchema.shape({
id: number().isRequired(),age: number().isRequired()
})
相当于:
const someSchema = Yup.object().shape({
id: number().isRequired(),// notice how 'id' is overridden by child schema
name: string().isRequired(),age: number().isRequired()
})
另一种方法是使用 concat(schema)
通过组合两个架构来创建新架构实例:Yup documentation
mixed.concat(schema: Schema): Schema
通过组合两个模式创建模式的新实例。只能连接相同类型的模式。
const baseSchema = Yup.object().shape({
name: string().isRequired()
})
const someSchema = baseSchema.concat(
Yup.object().shape({
age: number().isRequired()
}))
// someSchema will be equipped with both `name` and `age` attributes
请注意,concat
仅在两个架构对象具有不同属性或具有完全相同类型的相同属性时才有效。