jaredpalmer / formik

Build forms in React, without the tears 😭
https://formik.org
Apache License 2.0
33.9k stars 2.79k forks source link

Get validating state of individual components #3933

Open LassazVegaz opened 9 months ago

LassazVegaz commented 9 months ago

Feature request

Current Behavior

There is no API provided to get the validating state of individual controls. Here validating state means if the field is currently being validated or not.

Desired Behavior

An API to check if the field is being validated. A very generic use case is, in a signup form, checking if the email address already exists in the system. This is an asynchronous validation. This can be shown by a small spinner next to the email field.

Suggested Solution

I assume this cannot be done without individually specified validators. This means, developers should be able to define validators individually for any control. This does not mean form-level (global) validation should be committed. Both are needed. When individual validators are defined internals of Formik can track if the field is being validated.

I got this idea from the TanStack form. Check this example which uses Yup. However, defining validators at the controller level in the UI does not look like a good idea. It is better to separate UI and validations.

I am imagining a solution like this,

const validationSchemma = Yup.object().shape({
  password: Yup.string().required("Required"),
});

const initialValues = {
  password: "",
  email: "",
};

const form = useFormik({
  initialValues,
  // validationSchema: validationSchemma, --> current solution
  validotors: { // --> expected solution
    globalValidation: validationSchemma,
    individualValidators: {
      email: Yup.string()
        .email("Invalid email")
        .test("email", "Email already exists", async (value) => {
          // async validation
        }),
      // password: --> can define individual validators for any field
    },
  },
  onSubmit: async (values) => {
    console.log(values);
  },
});

form.isValidating.email; // --> checking validating status

I hope in this Formik internals can track individual validation states. I use useFormik only, therefore I am not sure how to do this with Formik components.

Who does this impact? Who is this for?

Any developer that needs to know individual component's validating state.

Describe alternatives you've considered

I considered using the Tanstack Form. But I do not like it. Their maintainers have weird attitudes. I love formik. I wanna contribute if this feature can be implemented. Anyway, I cannot think of a way to do this with the current APIs given by Formik

Additional context

Nothing else

Thanks for your great work ❤️