In this tutorial, we will learn how to validate forms in React using the Formik and React Hook Form libraries. We will also display error messages during validation.
You will learn:
- How to install and use Formik and React Hook Form libraries.
- How to validate form inputs.
- How to display error messages.
Prerequisites:
- Basic understanding of JavaScript.
- Knowledge of React basics.
Formik is a small library that helps with handling form state, form submission, and form validation.
To start, install Formik using npm:
npm install formik --save
Formik uses a property called 'validationSchema' for validating the form. This property takes a Yup object. Yup is a JavaScript schema builder for value parsing and validation.
Install Yup using npm:
npm install yup --save
Formik automatically ties into the validationSchema and will update an 'errors' object for you, which you can use to show error messages.
React Hook Form is a library that allows you to abstract form state logic to a custom hook.
Install React Hook Form using npm:
npm install react-hook-form
React Hook Form uses 'register' function for registering input fields for validation.
React Hook Form provides 'errors' object which can be used to display error messages.
import React from 'react';
import { Formik, Field, Form, ErrorMessage } from 'formik';
import * as Yup from 'yup';
// Validation schema using Yup
const validationSchema = Yup.object().shape({
name: Yup.string()
.required('Name is required'), // Validation rule: field is required
email: Yup.string()
.email('Email is invalid') // Validation rule: field has to be a valid email
.required('Email is required'), // Validation rule: field is required
});
export function App() {
return (
<Formik
initialValues={{ name: '', email: '' }}
validationSchema={validationSchema}
onSubmit={fields => {
alert('Form submitted');
}}
>
{({ errors, status, touched }) => (
<Form>
<div>
<label htmlFor="name">Name</label>
<Field name="name" type="text" className={'form-control' + (errors.name && touched.name ? ' is-invalid' : '')} />
<ErrorMessage name="name" component="div" className="invalid-feedback" />
</div>
<div>
<label htmlFor="email">Email</label>
<Field name="email" type="text" className={'form-control' + (errors.email && touched.email ? ' is-invalid' : '')} />
<ErrorMessage name="email" component="div" className="invalid-feedback" />
</div>
<div>
<button type="submit">Submit</button>
</div>
</Form>
)}
</Formik>
);
}
import React from 'react';
import { useForm } from 'react-hook-form';
export function App() {
const { register, handleSubmit, errors } = useForm();
return (
<form onSubmit={handleSubmit(data => alert('Form submitted'))}>
<div>
<label htmlFor="name">Name</label>
<input type="text" name="name" ref={register({ required: true })} />
{errors.name && <p>Name is required</p>}
</div>
<div>
<label htmlFor="email">Email</label>
<input name="email" ref={register({ required: true, pattern: /^\S+@\S+$/i })} />
{errors.email && <p>Valid email is required</p>}
</div>
<button type="submit">Submit</button>
</form>
);
}
In this tutorial, we covered form validation in React using Formik and React Hook Form libraries. We learned how to validate form inputs and display error messages.
Next steps:
- Explore more advanced features of Formik and React Hook Form.
- Practice creating complex forms with validation.
Additional resources:
- Formik Documentation
- React Hook Form Documentation
Remember, practice makes perfect. Happy coding!