React hook form schema validation using yup; React Hook Form is a library to validate forms 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. In the previous article, we have seen we have to add the rules in the form fields tag, if we have a large form with complex validation then the form will be messy.
React Hook Form supports external schema-based form validation with Yup, React Hook Form also supports other schema-based validation libraries but for now in this example, we are using Yup. if you want to validate the react form without Yup please check this article
You can download/clone the working example https://github.com/technostuf/react-hook-form-validation
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-hook-form-validation
The above command will create a new folder named react-hook-form-validation 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 create and validate the ReactJS forms, install it from npm, it is a minimal library working without any other dependency.
npm install react-hook-form --save
Install Yup
library for schema-based validation
Install yup into your project using the below command
npm install @hookform/resolvers yup --save
Add code to the file
Create a component file FormComponent.js, and import it into App.js. We have created a separate file to demonstrate a form validation.
import React from "react";
import { useForm } from 'react-hook-form';
import { yupResolver } from '@hookform/resolvers/yup';
import * as yup from "yup";
const phoneRegExp = /^((\\+[1-9]{1,4}[ \\-]*)|(\\([0-9]{2,3}\\)[ \\-]*)|([0-9]{2,4})[ \\-]*)*?[0-9]{3,4}?[ \\-]*[0-9]{3,4}?$/
const validationSchema = yup.object().shape({
firstName: yup.string()
.required('First Name is required'),
lastName: yup.string()
.required('Last name is required'),
email: yup.string()
.required('Email is required')
.email('Email is invalid'),
mobile: yup.string().matches(phoneRegExp, 'Phone number is not valid')
});
const FormComponent = () => {
const { register, handleSubmit, reset, formState: { errors } } = useForm({
resolver: yupResolver(validationSchema)
});
const onSubmit = data => {
console.log(JSON.stringify(data));
};
return (
<div className="container">
<div className="row register-form ">
<h1>React hook form schema validation with yup - 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')}
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')}
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')}
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')}
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;
Yup is a schema-based validation library, Yup schema is extremely expressive and allows complex, interdependent validations, or value transformation.
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 will be 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
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 hook form schema validation using yup](https://technostuf.com/wp-content/uploads/2022/04/react-hook-form-with-yup.gif)
You can download/clone the working example.
https://github.com/technostuf/react-hook-form-validation
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