【问题标题】:Yup conditional validation based on parent object schema是的,基于父对象模式的条件验证
【发布时间】:2020-02-29 21:12:29
【问题描述】:

我正在使用 array().of 方法创建 Yup 验证模式,我需要根据来自外部模式对象的值在该数组中设置一些验证规则。我怎样才能获得对该值的引用?


const termsSchema = Yup.object().shape({
  termType: Yup.string().when('condition', {
    is: true,
    then: Yup.string()
      .required('Type is required'),
  }),
});

const schema = Yup.object().shape({
  condition: Yup.boolean()
    .required('Error'),
  terms: Yup.array().of(termsSchema),
});

【问题讨论】:

  • 我很确定这是不可能的,因为 according to the documentation.when() 允许您“根据同级或同级子字段调整架构。”
  • is: (value) => value == true. 你可以为is 使用回调,它可以访问value,你可以随意使用它。

标签: javascript formik yup


【解决方案1】:

可以使用 when 通过回调函数访问 Yup 架构之外的变量。您可以将任何虚拟字段用于第一个参数,因为其目的只是触发回调。一旦满足条件,then 之后的验证规则将适用。更多信息请参考Yup

let outside = true

const schema = Yup.object().shape({
  dummy:Yup.string(),
  terms: Yup.array().of(termsSchema).when("dummy", {
    is: (value) => 
      outside === true,
      then: Yup.number().required("Please provide info")
  }),
});

【讨论】:

    【解决方案2】:

    很确定您已经找到了解决方案/解决方法。然而,这种方法可能会派上用场,以便人们解决这个问题以寻求潜在的解决方案:

    由于您需要嵌套架构的同级字段的值,您可以使用when 创建嵌套架构,例如:

    const schema = Yup.object().shape({
      condition: Yup.boolean()
        .required('Error'),
      terms: mixed().when('condition',(value) => {
         // use any logic you need to build/modify the returned schema
         return array().of(termsSchema)
     }),
    });
    

    使用 .when 访问嵌套字段是一个 current limitation 是的,但是这种方法对我有用。我也很好奇你做了什么来解决这个问题。

    【讨论】:

      猜你喜欢
      • 2017-08-12
      • 1970-01-01
      • 2020-07-28
      • 2014-05-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-26
      • 1970-01-01
      相关资源
      最近更新 更多