How to pre-check or pre-validate form data before submission in React Hook Form?

In React Hook Form, when a form has errors in it, it won’t emit the submit event normally.
However, sometimes it is important to manually handle form validity such as when using validation information from a server.
In that case, it is possible to manually handle the validation via the “mode” property of useForm options by setting it to “onChange”. An example below shows how to do this.
// tsx
import { DOMAttributes } from ‘react’;
import { FormProvider, useForm } from ‘react-hook-form’;
export const MyForm = () => {
  const useFormMethods = useForm<any>({
    mode: ‘onChange’,
  });
  const {
    handleSubmit,
    clearErrors,
  } = useFormMethods;
  const onValidSubmit = useCallback(async (data: any) => {
    // Submit logic
  }, []);
  type OnFormSubmit = DOMAttributes<HTMLFormElement>[‘onSubmit’];
  type OnFormSubmitEvent = Parameters<NonNullable<OnFormSubmit>>[0];
  const onSubmit: OnFormSubmit = useCallback(
    (ev: OnFormSubmitEvent) => {
      // Manually validate values. If OK, proceed:
      clearErrors();
      handleSubmit(onValidSubmit)(ev);
    },
    [clearErrors, handleSubmit, onSubmit],
  );
  return (
    <FormProvider {…useFormMethods}>
      <>
        <form onSubmit={onSubmit}>
    </FormProvider>
  );
}

Leave a Reply

Your email address will not be published. Required fields are marked *