Categories
JavaScript React

React Hook Form – a Good React Form Validation Library

Spread the love

Handling form input values and form validation is a pain with React apps.

We’ve to figure it out all by ourselves. Fortunately, there’re good packages out there to help us solve this problem easy.

In this article, we’ll look at how we can use the React Hook Form library as our React app form validation library.

Getting Started

To get started, we run:

npm install react-hook-form

Then we can use it to add a form with a required field by writing:

import React from "react";
import { useForm } from "react-hook-form";

export default function App() {
  const { register, handleSubmit, watch, errors } = useForm();
  const onSubmit = data => console.log(data);
  return (
    <div className="App">
      <form onSubmit={handleSubmit(onSubmit)}>
        <input name="requiredField" ref={register({ required: true })} />
        <br />
        {errors.requiredField && <span>This field is required</span>}
        <br />
        <input type="submit" />
      </form>
    </div>
  );
}

In the code above, we used the useForm hook from the react-hook-form React form validation library to return the register function to register input as a ref. We pass in { required: true } to make the form field required.

Submission won’t be made until all form fields have valid input values.

The handleSubmit function is used as our form submit handler. We just log the values that are entered. data has the input value for each field.

errors has an object with the errors. It’s smart enough to only display when it’s touched.

Validating Input Format

We can validate input patterns by passing in various properties to the object that we pass into the register function.

To add form validation for various formats and regex patterns, we can write:

import React from "react";
import { useForm } from "react-hook-form";

export default function App() {
  const { register, handleSubmit, watch, errors } = useForm();
  const onSubmit = data => console.log(data);
  return (
    <div className="App">
      <form onSubmit={handleSubmit(onSubmit)}>
        <input
          name="firstName"
          ref={register({ required: true, maxLength: 20 })}
        />
        <br />
        {errors.firstName && <span>Invalid first name</span>}
        <br />
        <input name="lastName" ref={register({ pattern: /^[A-Za-z]+$/i })} />
        <br />
        {errors.lastName && <span>Invalid last name</span>}
        <br />
        <input name="age" type="number" ref={register({ min: 18, max: 99 })} />
        <br />
        {errors.age && <span>Age is must be between 18 and 99</span>}
        <br />
        <input type="submit" />
      </form>
    </div>
  );
}

We have maxLength validation for the firstName input field to make sure that the length of the firstName input value never exceeds 20.

lastName has the pattern property in the object that we pass into register to make sure that we only enter alphabet characters as the value of lastName.

To validate age, we have the min and max values to restrict the range of age to be between 18 and 99.

We also display an error message for each input field to display an error message when the format doesn’t match the ones specified by the properties.

React Hook Form is a great React form validation library that lets us handle input value changes and form validation less code than the alternatives.

Leave a Reply

Your email address will not be published. Required fields are marked *