我找了一下,不知道这是否可行。本质上,我想用YUP使用一个状态钩子来验证一个Formik表单,这个状态钩子不是表单值。
validationSchema={Yup.object({
comments: Yup.string()
.when(approvalState, {
is: false,
then: Yup.string().required('Comments are required when denying an approval.'),
}),
})}
这里是表单字段,它基本上是一个文本框。
这里是提交按钮,它将状态值改为真。
<button className='buttonPrimary' type='submit' onClick={()=> setApprovalState(true)} disabled={formik.isSubmitting}>Approve</button>
这里是另一个按钮,也是提交按钮,将状态值改为false。
<button className={`buttonSecondary ${styles.marginRight}`} type='submit' onClick={()=> setApprovalState(false)} disabled={formik.isSubmitting}>Deny</button>
状态值更新得很好,有什么办法可以根据一块状态值来有条件地验证文本框是否为必填项?
您的解决方案将在以下情况下工作 approvalState
是在formik的值。
Yup.object({
comments: Yup.string()
.when('approvalState', { // Change approvalState to string
is: false,
then: Yup.string().required('Comments are required when denying an approval.'),
}),
})
或者你可以这样做:
Yup.object({
comments: approvalState
? Yup.string()
: Yup.string().required('Comments are required when denying an approval.')
})