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…

Tutorial 2 of 5 5 resources in this section

Section overview

5 resources

Explores 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

  1. Create a form with three fields: Name, Email, and Password. Validate all fields using both Formik and React Hook Form.
  2. Display different error messages for different validation rules.
  3. 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.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Keyword Density Checker

Analyze keyword density for SEO optimization.

Use tool

Word to PDF Converter

Easily convert Word documents to PDFs.

Use tool

Random String Generator

Generate random alphanumeric strings for API keys or unique IDs.

Use tool

JSON Formatter & Validator

Beautify, minify, and validate JSON data.

Use tool

Interest/EMI Calculator

Calculate interest and EMI for loans and investments.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI 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 article

AI 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 article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help