'Use debounce and async validation only at one field with Formik and yup

I'm working with a registration form for my application and, to put you in context, I have the following features/functionality enabled:

  • I am using Formik + Yup for validation.
  • I am using asynchronous validation to check if emails exist in my bbdd.
  • I use loadash/debounce to validate the email within .5s of stop writing.

These are my validationSchema

const validationSchema = Yup.object().shape({
  nombre: Yup.string().restOfRules(),
  apellidos: Yup.string().restOfRules(),
  email: Yup.string().restOfRules()
    .test(
      'Email duplicado',
      'Este email ya está en uso.',
      async (value) =>
        new Promise((resolve) => validateEmail(value || '', resolve))
    ),
  });

and my email validator function with debounce:

const validateEmail = debounce(
  async (value: string, resolve: (val: boolean) => void) => {
    let error = '';

    const res: any = await checkIfEmailExists({ email: value });

    if (res?.data?.exists !== false)
        error = 'Este email ya está en uso.';

    return resolve(error === '');
  },
  500
);

Because of all this I run into the following problems:

1. All fields take .5s to validate, not just the email. In this step of the form, my users enter their email, first name and last name, and the problem is that I need the validation of the first name and last name to be instantaneous.

As formik validates all the fields at the same time, it takes .5s to validate also the email, so the interface shows that the name is correct moments after typing it.

2. The asynchronous validation is executed even when I don't type in the email field. As I commented in the previous step, since formik validates all the fields at the same time, every time I type the first and last name, it executes a request to my server to validate the email, which I would like to avoid.

I know that the continuous validation of all the fields by Formik is something intentional by the creator of the library himself, so I understand that my second problem is something that can't be avoided at all, but I do worry about the first thing....

So: Is there any way to specify Formik/Yup to execute the validation of a field only when its value is changing (and, of course, before submitting the form)?.

Thanks in advance!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source