Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

169
Views
Manually set a field to touched onChange instead of onBlur with formik or can I manually call a function before setting an event handler?

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

  1. A nearby checkbox is checked (which enables the input)
  2. The input's onChange has fired once (key event has occurred)
  3. The input is empty.

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?

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!