首页 > 解决方案 > Formik 尝试验证不可见字段

问题描述

我在使用 Formik Validation Schema 时遇到了这个问题。我的表单有 3 种形状,每个形状中都有几个字段,具体取决于给定的参数类型和 upperType。问题是当我尝试提交表单时,如果以下字段之一不可见且没有值,则 submitForm 函数不会触发。我已经尽可能地设置了条件逻辑,那么为什么 .nullable 不允许表单提交?

形状示例:

type === expire => only endDate

类型 === 永久 => 下 & 上(取决于上类型)& 开始日期

等等

问题是当只有 endDate 可见时,表单仍会尝试验证其余的表单字段,并且与表单的其他形状相同。我的验证逻辑不正确吗?

export const validationSchema = (type: string, upperType: RangeType | undefined) => {
  const result = Yup.object({
    lower: Yup.string().when([], {
      is: type !== 'expire',
      then: Yup.string().required(errorMessages.lowerRequired),
      otherwise: Yup.string().nullable(true)
    }),
    upper: Yup.string().when([], {
      is: (type !== 'expire' && (upperType === ASYMMETRICAL || upperType === OUTER)),
      then: Yup.string().required(errorMessages.upperRequired),
      otherwise: Yup.string().nullable(true)
    }),
    startDate: Yup.date()
      .when([], {
        is: type === 'permanent' || type === 'temporary',
        then: Yup.date().nullable(true)
      })
      .max(dateMaxServer(), errorMessages.dateMax),
    endDate: Yup.date().when([], {
      is: type === 'temporary' || type === 'expire',
      then: Yup.date().required(errorMessages.dateRequired),
      otherwise: Yup.date().nullable(true)
    }),
  })
  return result
}

标签: reactjstypescriptformikyup

解决方案


如果您想以自定义方式进行比较,我认为期望功能。

is: type !== 'expire', //always resolves to **true** if it is used without function

试试看。

代替

is: type !== 'expire'

is: ()=>type !== 'expire',

推荐阅读