I have a problem with a text field in my React+Formik component.
I need the field's touched property to be set when onChange is fired. The reason for this is that I'm doing some validation on the form, the conditions for the field to error are as follows
Formik sets touched onBlur, not onChange. The problem with this is that the user is able to check the box, type something, delete it, and then focus another input - This does not cause the error to show because the touched prop of the field has not been set, so the if statement in the validation function evaluates to false as touched =/= true.
This means the field in invalid but the error isn't displayed to the user, which is bad UX.
Validation function
const validate = (values: PostJobForm) => {
const errors: any = {
compensation: {},
};
if (
values.compensation.hasBonus &&
formik.touched?.compensation?.annualBonus &&
!values.compensation.annualBonus
) {
errors.compensation.annualBonus = "Required";
}
return errors;
};
What I really need to be able to do is be able to call formik's setFieldTouched function before the handleChange function is called. However I'm not sure if it's possible to do this in the onChange event listner on the input element?
<input
name="compensation.annualBonus"
onChange={formik.handleChange}
onBlur={formik.handleBlur}
className="basic-input w-full mt-2"
disabled={!formik.values.compensation.hasBonus}
value={formik.values.compensation.annualBonus}
/>
Instead of the onChange above I would do something like
onChange={() => {formik.setFieldTouched('compensation.annualBonus'); formik.handleChange}}
Which would set the touched prop and then use the handleChange function as the event handler.
But I'm sure that's not possible. What can I do instead?