Using Formik with Yup for Form Validation in React: Conditional Validation Not Firing
I'm working through a tutorial and I need some guidance on I need help solving I'm currently implementing a React form using Formik for state management and Yup for validation schema... The form has a conditional field that should only be validated if a specific checkbox is checked. I set up the validation schema to accommodate this, but it seems that the validation for the conditional field is not firing as expected. Hereβs a simplified version of my code: ```javascript import React from 'react'; import { Formik, Form, Field, ErrorMessage } from 'formik'; import * as Yup from 'yup'; const validationSchema = Yup.object().shape({ name: Yup.string().required('Name is required'), email: Yup.string().email('Invalid email').required('Email is required'), agree: Yup.boolean().oneOf([true], 'You must accept the terms and conditions'), additionalInfo: Yup.string().when('agree', { is: true, then: Yup.string().required('Additional info is required when agreeing to terms'), }), }); const MyForm = () => { return ( <Formik initialValues={{ name: '', email: '', agree: false, additionalInfo: '' }} validationSchema={validationSchema} onSubmit={(values) => { console.log(values); }} > {({ values }) => ( <Form> <div> <label htmlFor="name">Name</label> <Field name="name" type="text" /> <ErrorMessage name="name" component="div" /> </div> <div> <label htmlFor="email">Email</label> <Field name="email" type="email" /> <ErrorMessage name="email" component="div" /> </div> <div> <label> <Field name="agree" type="checkbox" /> I agree to the terms </label> <ErrorMessage name="agree" component="div" /> </div> {values.agree && ( <div> <label htmlFor="additionalInfo">Additional Info</label> <Field name="additionalInfo" type="text" /> <ErrorMessage name="additionalInfo" component="div" /> </div> )} <button type="submit">Submit</button> </Form> )} </Formik> ); }; export default MyForm; ``` The issue I'm facing is that the `additionalInfo` field validation does not trigger at all when the checkbox is checked. Instead, it seems to validate only when the form is submitted, and if the checkbox is unchecked, it does not show the required error message regardless of whether the field is filled or not. I've tried using the `validateOnChange` and `validateOnBlur` props on Formik, but I still don't see the expected behavior. Iβm using Formik version 2.2.6 and Yup version 0.32.11. Any insights on why the conditional validation might not be working as planned? Is there something specific that Iβm missing in the setup? Any ideas how to fix this? This is my first time working with Javascript LTS. Thanks, I really appreciate it! I'm coming from a different tech stack and learning Javascript. I appreciate any insights!