数组对象中第一个和最后一个元素的Yup验证

3

我在我的表单(Formik)中有一个字段,其中包含一个由每个对象两个时间戳组成的数组。 我的验证模式现在适用于数组中的所有元素,但目标是仅检查数组中的第一个和最后一个对象,所有其他对象都可以为空。 数组的长度会动态变化。 我该怎么办?

"timeslots": [
{
  "startTime": "2021-10-31T22:30:00.000Z",
  "endTime": "2021-11-01T00:30:00.000Z"
},
{
  "startTime": "",
  "endTime": ""
},
{
  "startTime": "2021-11-02T22:30:00.000Z",
  "endTime": "2021-11-03T00:00:00.000Z"
}]

只有所有对象都填满了时间戳,这个才能工作:

validationSchema={() =>
                Yup.lazy(({ timeslots }) =>
                    ? Yup.object({
                        timeslots:
                            timeslots.length > 0 &&
                            Yup.array().of(
                            Yup.object().shape({
                                    startTime: Yup.string().required(INVALID_FORM_MESSAGE.requiredField),
                                            endTime: Yup.string().required(INVALID_FORM_MESSAGE.requiredField),
                                        }),
                                    ),
1个回答

4

我不知道有什么方法可以使用shape()来实现您想要的功能,但是您可以使用测试函数代替:

validationSchema={
  Yup.lazy(({ timeslots }) =>
    Yup.object({
      timeslots: Yup.array()
        .of(
          Yup.object().shape({
            startTime: Yup.string(),
            endTime: Yup.string()
          })
        )
        .test({
          name: 'first-and-last',
          message: INVALID_FORM_MESSAGE.requiredField,
          test: val => 
            val.every(
              ({ startTime, endTime }, index) => {
                if (index === 0 || index === val.length - 1) {
                  return !!startTime && !!endTime;
                }
                return true;
              }
            )
        })
    })
)}


1
非常感谢!我一直都错过了这个“.every”的东西。它完美地工作了! - Vicyn

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接