We're using Yup to validate Formik fields. For one field, I need it to be required, or not, depending on the value of a state variable in the parent component; not another Formik field.
Roughly what I'd like to do is:
// in the parent component
import validationSchema from './validationSchema.ts'
const MyComponent = () => {
const [someState, setState] = useState();
// ...
<Formik
validationSchema={validationSchema}
// ...
}
// then, in the validator
// (find some way to make `someState` available here)
export const validationSchema = Yup.object().shape({
myField: Yup.string().test('required', 'Field is required', value => {
if (someState) {
return false // field is required if someState is truthy
} else {
return true // field is not required if someState is falsey
}
//...
Does anyone know what the correct approach to this is? I essentially need to be able to pass state in to the validation schema when it's invoked.