React Hook Form is a library for form building in ReactJS, it is easier to validate a form using react hook form library with a few lines of code we can validate a form, Today we will create a simple form and validate each field, Fields are first name, last name, email, mobile number and validate on submit the form.
You can download/clone the working example https://github.com/technostuf/react-form-hook-validation-example
- Create a React application
- Install react-hook-form library
- Add code to the file
- Run a React application
Create a React application
Create a React app using the below command. Open your terminal and move to your project folder and run the below command.
npx create-react-app react-form-hook-validation-example
The above command will create a new folder named react-form-hook-validation-example and now you need to move into that folder, use the below command to change the directory.
cd react-form-hook-validation-example
Install react-hook-form library
React Hook Form is a library we will use to validate the ReactJS forms, install it from npm, it is a minimal library working without any other dependency
npm install react-hook-form --save
Add code to the file
Create a component file FormComponent.js, and import it into App.js. We have created this separate to demonstrate a form validation.
import React from "react";
import { useForm } from 'react-hook-form';
const FormComponent = () => {
const { register, handleSubmit, reset, formState: { errors } } = useForm();
const onSubmit = data => {
console.log(JSON.stringify(data));
};
return (
<div className="container">
<div className="row register-form ">
<h1>React hook form validation - technostuf.com</h1>
<div className="col-md-6" >
<form onSubmit={handleSubmit(onSubmit)}>
<div className="form-group">
<label className="control-label">First Name</label>
<input
name="firstName"
type="text"
{...register('firstName', {
required: {
value: true,
message: "Please enter the first name"
},
maxLength: {
value: 20,
message: "Maximum 20 characters allowed"
},
minLength: {
value: 2,
message: "Minimum 2 characters required"
}
})}
className={`form-control ${errors.firstName ? 'is-invalid' : ''}`}
/>
<div className="invalid-feedback">{errors.firstName?.message}</div>
</div>
<div className="form-group">
<label>Last Name</label>
<input
name="lastName"
type="text"
{...register('lastName', {
required: {
value: true,
message: "Please enter the last name"
},
maxLength: {
value: 20,
message: "Maximum 20 characters allowed"
},
minLength: {
value: 2,
message: "Minimum 2 characters required"
}
})}
className={`form-control ${errors.lastName ? 'is-invalid' : ''}`}
/>
<div className="invalid-feedback">{errors.lastName?.message}</div>
</div>
<div className="form-group">
<label>Email</label>
<input
name="email"
type="text"
{...register('email', {
required: {
value: true,
message: "Please enter the email address"
},
pattern: {
value: /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/i,
message: "Please enter a valid email address"
}
})}
className={`form-control ${errors.email ? 'is-invalid' : ''}`}
/>
<div className="invalid-feedback">{errors.email?.message}</div>
</div>
<div className="form-group">
<label>Mobile</label>
<input
name="mobile"
type="text"
{...register('mobile', {
required: {
value: true,
message: "Please enter the mobile number"
},
pattern: {
value: /^[0-9+-]+$/,
message: "Please enter the valid phone number"
},
})}
className={`form-control ${errors.mobile ? 'is-invalid' : ''}`}
/>
<div className="invalid-feedback">{errors.mobile?.message}</div>
</div>
<div className="form-group">
<button type="submit" className="btn btn-primary">
Register
</button>
<button type="button" onClick={() => reset()}
className="btn btn-warning float-right" >
Reset
</button>
</div>
</form>
</div >
</div >
</div>
)
}
export default FormComponent;
The First Step is to import the useForm from react-hook-form
import { useForm } from 'react-hook-form';
The useForm() hook function returns an object with methods for working with a form, register, handleSubmit, reset, formstate, etc… are the method of useForm, see above code
const { register, handleSubmit, reset, formState: { errors } } = useForm();
onSubmit: onSubmit method is called when the form is valid and submitted, We can access the form data inside the onSubmit function
register: We have used the register method in the form input field, register method will register the input to validate the field, where we need to pass the validation rules array, and we need to register each field we need to validate.
<input name="firstName" type="text"
{...register('firstName', {
required: {
value: true,
message: "Please enter the first name"
},
maxLength: {
value: 20,
message: "Maximum 20 characters allowed"
},
minLength: {
value: 2,
message: "Minimum 2 characters required"
}
})}
className={`form-control ${errors.firstName ? 'is-invalid' : ''}`}
/>
The explanation for the above example: The first parameter is the input field name and the second parameter is the validation rules array, We have set required true which means this is a required field, the message is the error message you want to show to the frontend user
List of validation rules supported:
- required
- min
- max
- minLength
- maxLength
- pattern
- validate
Finally, you have to import both files into App.js.
import './App.css';
import FormComponent from './FormComponent';
function App() {
return (
<div className="App">
<FormComponent />
</div>
);
}
export default App;
Run a React application
Run the React application using the following command.
npm start
After compilation, the program opens your browser and runs http://localhost:3000/
Output
![react-form hook validation](https://technostuf.com/wp-content/uploads/2022/04/react-form-validation.gif)
You can download/clone the working example.
https://github.com/technostuf/react-form-hook-validation-example
Related Post
- React Material UI Form example
- React Material UI Autocomplete with getting selected value
- React Area chart using recharts example
- React Pie chart using recharts with legend and custom label
- React google maps draggable marker example
- React datepicker using the most popular react-datepicker library
- React toast notification using react-toastify with example
- React responsive carousel slider with react-slick
- React tooltip using rc-tooltip with example
- React hook form schema validation using yup