【问题标题】:Extending one key on a Yup schema在 Yup 模式上扩展一个键
【发布时间】:2021-09-20 04:27:04
【问题描述】:

我正在创建一些 Yup 模式,例如:

    let validationSchema = yup.object({
      length: yup.number().min(1)
    });

有没有办法在它被声明后扩展它,就像我这样设置架构一样?

    let validationSchema = yup.object({
      length: yup.number().min(1).required(true)
    });

【问题讨论】:

    标签: validation yup


    【解决方案1】:

    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)通过组合两个schema来创建一个新的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 仅在两个架构对象具有不同属性或具有完全相同类型的相同属性时才有效。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-10
      • 1970-01-01
      • 2018-09-21
      相关资源
      最近更新 更多