是的嵌套模式验证

Yup nested schema validation

我正在尝试根据用户选择的 Select 选项有条件地验证一个对象,问题是我正在呈现一个货币列表并且很难将其设为必填字段,因为我必须传入一个空对象才能开始。

我的代码栈是 React、Formik 和 Yup(所有最新版本)。

对象模式

category: 'A',
details: {
   name: '',
   price: 0,
   stock: 0,
   currency: {
      label: '',
      code: '',
      symbol: '',
      alpha_2: '',
    }
}

Yup 模式

category: Yup.string().required('You must pick a category'),
details: Yup.object().when('category', {
  is: 'A',
  then: Yup.object({
       label: Yup.string().required(`Select the currency you're retailing in`),
        code: Yup.string().required(`Select the currency you're retailing in`),
        symbol: Yup.string().required(`Select the currency you're retailing in`),
        alpha_2: Yup.string().required(`Select the currency you're retailing in`),
    }),
})

使用上面的代码,表单正在通过验证并且货币对象有一个空值列表'',这是一个不希望的结果。

如何使架构触发验证?

您没有根据存储 label/code/symbol/alpha_2details.currency 进行验证。 在 schema.details 中,then 应该由一个 Yup.object 组成,其中另一个 Yup.object 存储在 currency 属性 中,然后定义您想要的验证label/code/symbol/alpha_2.

示例:

const yup = require("yup");

const schema = yup.object({
    category: yup.string().required('You must pick a category'),
    details: yup.object().when('category', {
        is: 'A',
        then: yup.object({
            currency: yup.object({
                label: yup.string().required(`[1] Select the currency you're retailing in`),
                code: yup.string().required(`[2] Select the currency you're retailing in`),
                symbol: yup.string().required(`[3] Select the currency you're retailing in`),
                alpha_2: yup.string().required(`[4] Select the currency you're retailing in`),
            })
        }),
    })
})

let state = {
    category: 'A',
    details: {
        name: '',
        price: 0,
        stock: 0,
        currency: {
            label: 'a',
            code: 'b',
            symbol: 'c',
            alpha_2: 'd',
        }
    }
}

schema.validate(state).then(console.log).catch(err => console.log(err))