1

I have searched around, not sure if this is possible. Essentially I am wanting to validate a formik form with YUP using a state hook that is not a form value.

 validationSchema={Yup.object({
          comments: Yup.string()
              .when(approvalState, {
                is: false,
                then: Yup.string().required('Comments are required when denying an approval.'),
              }),
        })}

Here is the form field, it is essentially a text box:

Here is the submit button, which changes the state value to true:

<button className='buttonPrimary' type='submit' onClick={()=> setApprovalState(true)} disabled={formik.isSubmitting}>Approve</button>

Here is the other button which also submits, changes the state value to false:

<button className={`buttonSecondary ${styles.marginRight}`} type='submit' onClick={()=> setApprovalState(false)} disabled={formik.isSubmitting}>Deny</button>

The state value updates fine, any way to conditionally validate the textbox as required based on a piece of state?

sm1l3y
  • 420
  • 2
  • 5
  • 15

2 Answers2

6

Your solution will work if approvalState is in values of 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.'),
               }),
})

Alternatively you can do:

Yup.object({
  comments: approvalState
              ? Yup.string()
              : Yup.string().required('Comments are required when denying an approval.')

})
Muhammad Ali
  • 2,538
  • 2
  • 16
  • 21
0

you can use state hook and render conditionally. please have a look at this thread https://stackoverflow.com/a/54919273/10154990

Varunkumar Gande
  • 599
  • 6
  • 18