React.js / React Forms and Validation
Validating Forms Using React Libraries
This tutorial will introduce you to form validation in React using popular libraries. You'll learn how to validate form inputs and display error messages using libraries such as F…
Section overview
5 resourcesExplores handling forms, input, and validation in React applications.
Validating Forms Using React Libraries
1. Introduction
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.
2. Step-by-Step Guide
Formik
Formik is a small library that helps with handling form state, form submission, and form validation.
Installation
To start, install Formik using npm:
npm install formik --save
Form Validation
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
Error Messages
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
React Hook Form is a library that allows you to abstract form state logic to a custom hook.
Installation
Install React Hook Form using npm:
npm install react-hook-form
Form Validation
React Hook Form uses 'register' function for registering input fields for validation.
Error Messages
React Hook Form provides 'errors' object which can be used to display error messages.
3. Code Examples
Formik
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>
);
}
React Hook Form
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>
);
}
4. Summary
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
5. Practice Exercises
- Create a form with three fields: Name, Email, and Password. Validate all fields using both Formik and React Hook Form.
- Display different error messages for different validation rules.
- Add more fields to the form and apply different validation rules.
Remember, practice makes perfect. Happy coding!
Need Help Implementing This?
We build custom systems, plugins, and scalable infrastructure.
Related topics
Keep learning with adjacent tracks.
Popular tools
Helpful utilities for quick tasks.
Latest articles
Fresh insights from the CodiWiki team.
AI in Drug Discovery: Accelerating Medical Breakthroughs
In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…
Read articleAI in Retail: Personalized Shopping and Inventory Management
In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …
Read articleAI in Public Safety: Predictive Policing and Crime Prevention
In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…
Read articleAI in Mental Health: Assisting with Therapy and Diagnostics
In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…
Read articleAI in Legal Compliance: Ensuring Regulatory Adherence
In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…
Read article