Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

164
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda