Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

165
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda