Validating Forms Using React Libraries

Tutorial 2 of 5

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!