DEV Community

Cover image for Form management with useForm (error messaging and data validation)
Yuko
Yuko

Posted on

Form management with useForm (error messaging and data validation)

This is my memo when I tried useForm which is custom hook for form managing when I create a photo storage web app(demo).

Basic syntax is the below

    const { register, handleSubmit } = useForm(optional arguments);
Enter fullscreen mode Exit fullscreen mode

There are other return values.

unregister, formState, watch, reset, resetField, setError, clearErrors, setValue, setFocus, getValues, getFieldState, trigger, and control (Please visit here for more detailed information)

This is the default values of their optional arguments.

    useForm({
      mode: 'onSubmit',
      reValidateMode: 'onChange',
      defaultValues: {},
      resolver: undefined,
      context: undefined,
      criteriaMode: "firstError",
      shouldFocusError: true,
      shouldUnregister: false,
      shouldUseNativeValidation: false,
      delayError: undefined
    })Here is an example of using useForm hook.
Enter fullscreen mode Exit fullscreen mode

Login form

Here is an example of login form.

    const {
        register,
        formState: { errors },
        handleSubmit,
      } = useForm({
        mode: "onBlur", 
      });
Enter fullscreen mode Exit fullscreen mode

register method

This method allows you to register an input or select element and apply validation rules to React Hook Form. Validation rules are all based on the HTML standard and also allow for custom validation methods.

Therefore, in this example, submit result is {email: inputValue} and input validation becomes false when the input is empty (Please visit here for more detailed information).

    <input {...register("email", { required: true })} />
Enter fullscreen mode Exit fullscreen mode

formState object

This object contains information about the entire form state. It helps you to keep on track with the userโ€™s interaction with your form application.

error is an object which includes ErrorMessage component to retrieve error message (Please visit here for more detailed information). Therefore, you will see an error message when you leave the input field empty.

    <input {...register("email", { required: true })} />

    {errors.email && <p>This is required</p>}
Enter fullscreen mode Exit fullscreen mode

handleSubmit

This function will receive the form data if form validation is successful.

You can use this function as a high order function.

    // onSubmit function
    const onSubmit = (data, e) => {
        // handle submit event
        setLoading(true);
        signInWithEmailAndPassword(auth, data.email, data.password)
          .then((userCredential) => {
            const user = userCredential.user;
            login(user.uid, user.auth.currentUser.accessToken);
            navigate("/loggedin/gallery", { replace: true });
          })
          .catch((error) => {
            const errorMessage = error.message;
            setLoginError(errorMessage);
          })
          .finally(() => setLoading(false));

    e.target.reset();
      };
    // inside of JSX
    <form onSubmit={handleSubmit(onSubmit)}>
Enter fullscreen mode Exit fullscreen mode

Please visit here for more detailed information.

Other validation example in Sing Up form

pattern

The regex pattern for the input.

This example is for email validation.

    <input {...register("email",
       {
           required: true,
           pattern:/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\ 
                   [\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]  
                   {1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+
                   [a-zA-Z]{2,}))$/,
       })}
     />
Enter fullscreen mode Exit fullscreen mode

validate

You can pass a callback function as the argument to validate, or you can pass an object of callback functions to validate all of them. This function will be executed on its own without depending on other validation rules include required attribute.

This example validates if the input value is same as passwordInput.

    <input type="password"
         {...register("password2", 
           {
             required: true,
             validate: (value) => value === passwordInput,
           })}
    />
Enter fullscreen mode Exit fullscreen mode

The whole code is available here.

Conclusion

This is my impression of using this hook.

๐Ÿ‘ easy to handle states such as inputs and error: We donโ€™t need to manage error by hand whereas normally we have to use useState or useReducer to manage form inputs and errors during form submission.
๐Ÿ‘ no more event.preventDefalut(): Sometimes I stupidly forget event.preventDefalut() during developments and get undesired page refresh but if you use useForm, useForm is smart enough to avoid this problem without any additional codes.

๐Ÿ‘Ž need installation: It is a little bit cumbersome to install and import this hook.
๐Ÿ‘Ž have to learn the Hook usage: You cannot avoid this process whatever you use but I think this is not so hard at least this time because the official website provides efficient documents with a lot of examples. For me, these examples worked well to understand how to use this hook.

Overall, I would like to say ๐Ÿ‘ because the pros outweigh the cons.

The original article is here

Top comments (0)