Mastering React Hook Form: Managing State, Form Submission, and Custom Validation [Part-2]

Unlock the full potential of React Hook Form with insights on state management, seamless form submissions, and crafting custom validation.

Vivek Patel
Simform Engineering
5 min readMay 21, 2024

--

React Hook Form streamlines form data management and enhances code efficiency by minimizing re-renders. It effectively handles form state using the useForm hook, which furnishes an object with essential properties and methods for state management.

Implementing Custom Validations

In our previous blog post, we covered the registration of input fields. Now, let’s delve into custom validations.

  • MaxLength and MinLength- The maximum value length to accept for this input.
 //For MaxLength
<input
{...register("test", {
maxLength: 2
})}
/>
//For MinLength
<input
{...register("test", {
minLength: 2
})}
/>
  • Regex:- The regex pattern for the input
<input
{...register('email', {
pattern: /^[^\s@]+@[^\s@]+\.[^\s@]+$/,
})}
type="text"
placeholder="Email"
id="email"
/>

Instead of continuously re-rendering the form with each keystroke to validate user input against a regex pattern using the useEffect hook in traditional forms, React Hook Form optimizes performance by leveraging the register method.

This configuration ensures instant validation without frequent re-renders. For more optional parameters, refer to the documentation.

Handling Form Submission in React Hook Form

The handleSubmit method accepts form data upon successful validation. It includes a callback function that executes upon form submission, inherently preventing the default form submission behavior. This eliminates the need to explicitly call the preventDefault()function when submitting the form.

Here is a code snippet demonstrating the implementation:

import './App.css'
import {useForm} from "react-hook-form";
function App() {
const {register,handleSubmit}=useForm();
const onSubmit = (data)=>{
console.log(data)
}
return (
<div className="App">
<h1>React Hook Form</h1>
<form onSubmit={handleSubmit(onSubmit)}>
<label>Email </label>
<input {...register(
"email",{
required:true,
pattern:/^[^\s@]+@[^\s@]+\.[^\s@]+$/
}
)} type={"text"}/>
<label> Name </label>
<input {...register("password")} type={"password"} />
<button type='submit'>Submit</button>
</form>
</div>
)
}

export default App

When you submit a form with invalid data, nothing will be logged in the console, and the input field with invalid data will automatically regain focus. This eliminates the need to disable the submit button while the data is invalid, as clicking it triggers validation.

Adding Custom Validation and Error Handling

The formState object encompasses details about the overall state of the form, enabling you to monitor user engagement. It offers access to values, errors, and various other properties that facilitate dynamic UI updates.

For instance, by utilizing the errors property from formState, you can present a tailored message if the form data is deemed invalid.

React Hook Form allows us to register each with a validation message by returning an object instead of a primitive.


import { useForm } from 'react-hook-form';
import { ErrorMessage } from '@hookform/error-message';
function App() {
const { register, handleSubmit, formState } = useForm();
const { errors } = formState;
const onSubmit = (data) => {
console.log(data);
};
return (
<div>
<h1>React Hook Form</h1>
<form onSubmit={handleSubmit(onSubmit)}>
<label>Email </label>
<input
{...register('email', {
required: {
value: true,
message: 'Email is Required',
},
pattern: {
value: /^[^\s@]+@[^\s@]+\.[^\s@]+$/,
message: 'Enter Valid Email',
},
})}
type={'text'}
/>
<ErrorMessage errors={errors} name='email' />

<label> Password </label>
<input
{...register('password', {
required: {
value: true,
message: 'Password is Requeired',
},
minLength: {
value: 8,
message: 'Password must be of 8 character',
},
})}
type={'password'}
/>
<ErrorMessage errors={errors} name='password' />

<button type='submit'>Submit</button>
</form>
</div>
);
}

export default App;

The <ErrorMessage/> component is a lightweight solution for displaying error messages associated with specific inputs. Install it via npm using the command: npm i @hookform/error-message.

To utilize this component effectively, you need to provide two props: errors, which contains the error messages, and name, which specifies the field associated with the error message. This ensures precise error handling and presentation within your application.

Custom Validation and Error Handling

Conditionally Disabling the Submit Button

React Hook Form simplifies form management by leveraging React hooks. With its intuitive API and performance optimizations, it allows you to disable the submit button during form submission, improving user experience.

  const { errors,isSubmitting } = formState;
<form onSubmit={handleSubmit(onSubmit)}>
<div>

<label>Email </label>
<input
{...register('email', {
required: {
value: true,
message: 'Email is Required',
},
pattern: {
value: /^[^\s@]+@[^\s@]+\.[^\s@]+$/,
message: 'Enter Valid Email',
},
})}
type={'text'}
/>
<ErrorMessage errors={errors} name='email' />
</div>
<div>

<label> Password </label>
<input
{...register('password', {
required: {
value: true,
message: 'Password is Required',
},
minLength: {
value: 8,
message: 'Password must be of 8 character',
},
})}
type={'password'}
/>
<ErrorMessage errors={errors} name='password' />
</div>

<button type="submit" disabled={isSubmitting}>
{isSubmitting ? 'Submitting...' : 'Submit'}
</button>
</form>

In this example, we define a simple form component using React Hook Form. The isSubmitting property provided by formState indicates whether the form is currently being submitted. We utilize this property to dynamically disable the submit button by setting its disabled attribute. Additionally, we update the button label to provide feedback to the user during the submission process.

In this example, isSubmitting from formState indicates whether the form is currently being submitted. We use this property to dynamically disable the submit button and update the button label to provide feedback during submission.

Disabling the Submit Button while submitting Data

Implementing Edit Form Functionality

Editing forms is common in web development, especially for updating user information. React Hook Form offers a robust solution for managing edit forms efficiently.

import React from 'react';
import { useForm } from 'react-hook-form';

function EditForm({ initialValues, onSubmit }) {
const { register, handleSubmit } = useForm({ defaultValues: initialValues });

return (
<form onSubmit={handleSubmit(onSubmit)}>
<input {...register('firstName')} />
<input {...register('lastName')} />
<button type="submit">Save Changes</button>
</form>
);
}

export default EditForm;

In this example, initialValues are passed to defaultValues to prepopulate the form fields with existing data. The defaultValues option ensures the form fields are initialized with the provided initial values.

Pre-filled Edit Form

You can check out the full source code on the Github Repository.

Conclusion

In this blog post, we explored various aspects of React Hook Form, including custom validations, form submission handling, error management, and conditional rendering of form elements. We also demonstrated how to implement edit form functionality efficiently.

With React Hook Form, developers can easily build robust and dynamic forms, making it a valuable tool for modern web development projects.

For more updates on the latest tools and technologies, follow the Simform Engineering Blog.

Follow us: Twitter | LinkedIn

--

--