reactjs - 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
}
解决方案
如果您想以自定义方式进行比较,我认为是期望功能。
is: type !== 'expire', //always resolves to **true** if it is used without function
试试看。
代替
is: type !== 'expire'
至
is: ()=>type !== 'expire',
推荐阅读
- angular - 错误:将 Angular 8 转换为 Angular Universal 时“无法读取未定义的属性‘种类’”
- python - python脚本中的正则表达式
- html - 为什么css文件正在加载空白页?
- excel - 有多个数据表时如何使用VBA修改所选Excel数据表中的记录
- python - 如何将浮点元组列表转换为Python中的字符串列表?
- java - XSLT FO 程序,将 XML 数据结构化问题转换为 PDF
- spring - 如何使用 netflix-eureka 获得注册的微服务
- jquery - 从数据表 SearchPanes 中剥离 HTML
- python - 如何从任何计算机编辑我的 MySQL 数据库?
- javascript - 无法将 SVG 编译为 Handlebars HTML 模板