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

246
Visualizações
Formik - Trigger validation from very first keypress

On the following StackBlitz I have a very simple form validation. The validation is done when the user clicks the submit button.

https://stackblitz.com/edit/react-formik-yup-example-uhdg-83teyn?file=Registration.js

import { ErrorMessage, Field, Form, Formik } from 'formik';
import React from 'react';
import * as Yup from 'yup';

export default () => {
  return (
    <Formik
      initialValues={{
        email: '',
      }}
      validationSchema={Yup.object().shape({
        email: Yup.string()
          .required('Email is required.')
          .email('Email is invalid.'),
      })}
      onSubmit={(values, { setSubmitting }) => {
        console.log(values);
        setSubmitting(false);
      }}
      enableReinitialize
    >
      {({ setFieldValue }) => (
        <Form>
          <div>
            <Field
              type="text"
              name="email"
              onChange={({ target: { value } }) => {
                console.log(value);
                setFieldValue('email', value);
              }}
            />
            <ErrorMessage name="email">
              {(error) => <div style={{ color: '#f00' }}>{error}</div>}
            </ErrorMessage>
          </div>
          <input type="submit" value="Submit" />
        </Form>
      )}
    </Formik>
  );
};

What I need is: Trigger the validation from the very first keypress (please notice that I'm not interested in validate it when the component is mounted, but just after the first keypress).

In other words: any keypress on any input inside the Formik should trigger the validation only for that specific input (not for others). It would be like the same effect like typing something in that input and then hitting Enter (because when hitting Enter we trigger the validation). But I want that to happen without hitting Enter.

Any idea on how to do that in a proper way?

Thanks!

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You can render Field with a child component such as <input> and handle its onKeyDown event. Rendering it this way gives you access to Formik's props which you can use to trigger validation.

         <Field name="email">
          {({ field, form }) => (
            <input
              onKeyDown={() => form.setFieldTouched('email')}
              {...field}
              id="email"
            />
          )}
        </Field>
        <ErrorMessage name="email">
          {(error) => <div style={{ color: '#f00' }}>{error}</div>}
        </ErrorMessage>
about 4 years ago · Juan Pablo Isaza Relatório
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