【问题标题】:Conditional Validation in a FieldArray using Formik & Yup使用 Formik 和 Yup 在字段数组中进行条件验证
【发布时间】:2020-05-10 02:29:40
【问题描述】:

我有一个具有嵌套值的 ScheduleForm,称为 hours_attributes。如果all_day 值为假,则各个小时有一个绑定条件,其中需要opens 值的存在。这是我当前架构的编写方式:

const ScheduleSchema = Yup.object().shape({
  name: Yup.string()
    .required('Required'),
  hours_attributes: Yup.array().of(
    Yup.object().shape({
      opens: Yup.object().when('all_day', {
      is: false,
      then: Yup.string().required('Required'),
      otherwise: Yup.string()
    }),
  }))
});

我不确定when 值是否期望该特定小时的all_day 值的索引。我需要某种索引吗?

【问题讨论】:

    标签: javascript reactjs formik yup


    【解决方案1】:

    尝试为when 的第二个参数提供一个函数:

    const ScheduleSchema = Yup.object().shape({
      name: Yup.string()
        .required('Required'),
      hours_attributes: Yup.array().of(
        Yup.object().shape({
          opens: Yup.boolean().when('all_day', (value, schema) =>
            value ? schema : schema.required('Required')),
      }))
    });
    

    如果上面的 sn-p 不起作用,则更改 hours_attributes 喜欢:

    
    Yup.object({
          opens: Yup.boolean().when('all_day', (value, schema) =>
            value ? schema : schema.required('Required'))
    }),
    
    

    如果您希望 opens 的值为真,那么:

    
    Yup.object({
          opens: Yup.boolean().when('all_day', (value, schema) =>
            value ? schema : schema.oneOf([true], 'Required'))
    }),
    
    

    【讨论】:

    • 什么是open类型?
    • 这是一个布尔值。
    • 这是否意味着当all_day 为假时opens 应该为真?如果是,那么您应该尝试:js Yup.object({ opens: Yup.boolean().when('all_day', (value, schema) => value ? schema : schema.oneOf([true], 'Opens should be true')) }),
    猜你喜欢
    • 2021-06-27
    • 1970-01-01
    • 2019-09-29
    • 2019-12-26
    • 2019-09-12
    • 1970-01-01
    • 2019-10-09
    • 2021-10-20
    • 2021-01-19
    相关资源
    最近更新 更多