【问题标题】:How to access a parent value inside an array in yup validation如何在 yup 验证中访问数组内的父值
【发布时间】:2020-05-14 16:27:58
【问题描述】:

我已经定义了一个 yup 架构

export const ValidationSchema = yup.object().shape({
    dateTo: yup
        .date()
        .required(MandatoryFieldMessage)

   uebernachtungen: yup.array().of(
     yup.object().shape({
     ort: yup
            .string()
            .trim()
            .max(100, Maximum100CharactersMessage)
            .required(MandatoryFieldMessage),

    bis: yup
            .date()
            .required(MandatoryFieldMessage)
            .max(yup.ref("dateTo"), "display message") }))
})

我只想在数组中使用dateTo 的值,这样uebernachtungen 中的所有bis 将不允许有大于dateTo 的值。

问题是我可以像ort 这样访问数组中的项目,但我不能像dateTo 这样访问它之外的项目。

所以在这种情况下 yup.ref("dateTo") 将返回 undefined 但yup.ref("ort") 将是正确的。似乎数组有自己的上下文,我无法访问父上下文。

这怎么可能?

【问题讨论】:

  • 您能否分享一个可重现的示例或至少发布整个架构。
  • @MuhammadAli 我更新了。
  • 你能告诉我你想用 dateTo 值实现什么吗?
  • 我希望uebernachtungen 中的所有bis 不允许具有大于dateTo 的值
  • 你用“test”试过什么吗? github.com/jquense/…

标签: validation yup


【解决方案1】:

我遇到了类似的问题。我成功地使用了这个解决方法。

想法:将整个表单数据作为上下文传递给架构并使用

访问任何表单值

this.options.context

 const ValidationSchema = yup.object().shape({
     dateTo: yup
         .date()
         .required(MandatoryFieldMessage)

     uebernachtungen: yup.array().of(
         yup.object().shape({
             ort: yup
                 .string()
                 .trim()
                 .max(100, Maximum100CharactersMessage)
                 .required(MandatoryFieldMessage),

             bis: yup
                 .date()
                 .required(MandatoryFieldMessage)
                 .test('dateToCheck', 'display message', function (value) {
                    // access dateTo from passed context
                   if(value>this.options.context.dateTo) return false
                   return true }),

         })) })

传递上下文

没有 Formik

在验证时将您的表单数据作为上下文发送

 ValidationSchema.validateSync(data, {context: form_data})

使用 Formik

使用 validate 而不是 validationSchema

将您的 表单数据 作为 validateYupSchema 中的第四个参数传递,该参数表示上下文并且可以稍后在架构中访问。

将您的 schema 作为 validateYupSchema 中的第二个参数传递。

    <Formik
      validate={(value) => {
        try {
          validateYupSchema(value, ValidationSchema, true, value);
        } catch (err) {
          return yupToFormErrors(err); //for rendering validation errors
        }

        return {};
      }}

       onSubmit={} />

【讨论】:

    【解决方案2】:

    如果我正确理解你的问题,这样的事情可能会奏效......

    Example of using test to get value from yup scheme

    【讨论】:

    • 这是我已经尝试过的。因为dateTo 不是数组上下文的一部分,所以这不会起作用。
    • 好吧,你可以使用 .test('test', 'test', function(item) { console.log(this.parent) }) 来获取它,其中 this.parent 是你的整个 yup 方案,所以你可以得到类似 const {dateTo} = this.parent
    猜你喜欢
    • 2022-10-14
    • 1970-01-01
    • 1970-01-01
    • 2021-12-21
    • 1970-01-01
    • 2019-02-28
    • 2019-07-23
    • 2018-12-19
    • 2021-06-27
    相关资源
    最近更新 更多