【问题标题】:Yup schema validation, where the one field is required depending on the value of another field是的架构验证,其中一个字段是必需的,具体取决于另一个字段的值
【发布时间】:2021-04-20 15:54:33
【问题描述】:

我有一个带有 react-hooks-form 的表单,并且正在尝试使用 yup 验证。 它现在工作正常,但我试图根据 product[0].hasVrnts 的值使字段“变体”成为必需的(当 hasVrnt===1 时应该需要变体)。 架构对象是:

const schema = yup.object().shape({
    date: yup.date().required(),
    beginDate: yup.date().required(),
    qty: yup.number().integer().positive(),
    product: yup.array().length(1).of(yup.object().shape({
        id: yup.number().integer().positive().required(),
        bom: yup.object({
            id: yup.number().integer().positive().required(),
            revId: yup.number().integer().positive().required(),
            code: yup.string(),
            name: yup.string()
        }),
        units: yup.array(),
        unitSet: yup.number().integer(),
        code: yup.string(),
        name: yup.string(),
        grp: yup.string(),
        hasVrnts: yup.number().integer()

    })).required(),

    variant: yup.array().length(1).of(yup.object().shape({
        id: yup.number().integer().positive(),
        code: yup.string(),
        name: yup.string(),
        unitSet: yup.number().integer(),
        units: yup.array(),
        recStats:yup.number().integer()
    })),
    rsrvd: yup.boolean() 
})

提前谢谢你们。

【问题讨论】:

    标签: reactjs yup


    【解决方案1】:

    我认为您可能需要查看 Yup 中的条件验证。 你可以使用 .when() 来获取它

    例如,您可以根据另一个字段(isBig)应用不同的字段计数验证策略:

    let schema = yup.object({
      isBig: yup.boolean(),
      count: yup.number().when('isBig', (isBig, schema) => {
        return isBig ? schema.min(5) : schema.min(0);
      }),
    });
    
    await schema.validate({ isBig: false, count: 4 });
    

    Yup 的官方文档中对此进行了描述: https://github.com/jquense/yup#mixedwhenkeys-string--arraystring-builder-object--value-schema-schema-schema

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-29
      • 2015-01-21
      • 1970-01-01
      • 2022-01-14
      • 1970-01-01
      • 1970-01-01
      • 2020-09-06
      • 2019-04-14
      相关资源
      最近更新 更多