可以绑定对象数组的bind formik验证错误

发布于 2025-01-22 15:58:57 字数 1162 浏览 2 评论 0原文

我有一个包含两个字段的表单:布尔值和对象数组。 当布尔值为真时,则应需要数组。 并且数组有两个字符串字段,一个字段不需要。

验证schecma

  const validationSchema = Yup.object().shape({
    boolVal: Yup.boolean().required().nullable(),
    arr: Yup.array().when('boolVal', {
      is: true,
      then: Yup.array(
        Yup.object().shape({
          str1: Yup.string().nullable(),
          str2: Yup.string().required()
          ),
        })
      ),
    }),
  })

initialValues

const formik = useFormik({
    initialValues: 
                  {
                    boolVal:false,
                    arr: [new MyObject()]
                  }
})

当我尝试为类似数组的特定元素呈现错误时,

formik.errors.arr[0]

我得到了此错误

未知的错误:对象无效,作为一个react子女(找到:带键{str2}的对象)。如果您打算渲染一个孩子的集合,请改用数组。

当我悬停在“ arr”上以查看它的类型时,它给了我

(属性)arr?:字符串|字符串[] | formikerrors< MyObject> []

当我使用此代码行渲染错误时,

{JSON.stringify(formik.errors.arr)}

它会显示我

{“ arr”:[{“ str2”:“需要str2”}]}

I have a form that contains two fields: boolean value and array of objects.
when the boolean value is true then the array should be required.
and the array have two string fields one is required and the other is not.

Validation Schecma

  const validationSchema = Yup.object().shape({
    boolVal: Yup.boolean().required().nullable(),
    arr: Yup.array().when('boolVal', {
      is: true,
      then: Yup.array(
        Yup.object().shape({
          str1: Yup.string().nullable(),
          str2: Yup.string().required()
          ),
        })
      ),
    }),
  })

initialValues

const formik = useFormik({
    initialValues: 
                  {
                    boolVal:false,
                    arr: [new MyObject()]
                  }
})

when i try to render the error for a specific element of the array like this

formik.errors.arr[0]

i got this error

Uncaught Error: Objects are not valid as a React child (found: object with keys {str2}). If you meant to render a collection of children, use an array instead.

and when i hover over the 'arr' to see the type of it, it gives me

(property) arr?: string | string[] | FormikErrors < MyObject > []

when i render the errors using this line of code

{JSON.stringify(formik.errors.arr)}

it shows me

{ "arr" : [ { "str2": "str2 is required" } ] }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

软甜啾 2025-01-29 15:58:58

我面临类似的问题,但我使用getin解决了它。

您可以通过以下方式使用:

import { getIn } from 'formik';

getIn(formik.errors, 'arr[0]');

”输入图像在此处“在此处”

引用formik文档: https://formik.org/docs/api/fieldarray#fieldarray-validation-gotchas

I was facing a similar issue but I solved it using getIn.

You can use it by following:

import { getIn } from 'formik';

getIn(formik.errors, 'arr[0]');

enter image description here

To refer formik documentation:https://formik.org/docs/api/fieldarray#fieldarray-validation-gotchas

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文