How to add validation of form input fields with React?

Sometimes, we want to add validation of form input fields with React.

In this article, we’ll look at how to add validation of form input fields with React.

How to add validation of form input fields with React?

To add validation of form input fields with React, we can use a library like React Hook Form.

We can install the library with:

npm i react-hook-form

Then we can use it by writing:

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

export default function App() {
  const {
    register,
    handleSubmit,
    formState: { errors }
  } = useForm();
  const onSubmit = (data) => console.log(data);

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input {...register("age", { pattern: /d+/ })} />
      {errors.age && <p>Please enter number for age.</p>}
      <input type="submit" />
    </form>
  );
}

We add an input and set the props of it by spreading the object returned by register.

We call register with the name attribute value of the input and an object with the regex pattern that we want to validate input value with.

Then we get the errors from the errors object.

And we set the onSubmit prop of the form element with the event handler function returned by handleSubmit, which only runs when all the input values are valid.

Conclusion

To add validation of form input fields with React, we can use a library like React Hook Form.