jaredpalmer / formik

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

Validate on field registration #2000

Open andyrichardson opened 5 years ago

andyrichardson commented 5 years ago

🚀 Feature request

Current Behavior

The following events do not cause validation to occur:

Desired Behavior

The following would occur on addition/change:

The following would occur on removal:

Suggested Solution

Add an effect to the useField hook to trigger a validation call when triggered/removed

OR

Add validateForm call to register/unregister field functions.

Who does this impact? Who is this for?

Describe alternatives you've considered

Proxying useField hook to do this manually - currently having to use this solution.

export const makeUseField = <S extends Record<string, any>>() => <
  K extends keyof S & string = Exclude<keyof S, number | symbol>
>(
  { name, validate }: UseFieldArgs<K>
) => {
  const { validateForm, isValid } = useFormikContext<any>();

  const formikUseFieldArgs = useMemo(
    () => ({ name, validate }),
    [validate],
  );

  useEffect(() => {
    validateForm();
    return () => validateForm();
  }, [validate, validateForm]);

  return useField(formikUseFieldArgs) as [FieldInputProps<S[K]>, FieldMetaProps<S[K]>];
};
jaredpalmer commented 4 years ago

Seems legit.