Categories
React Answers

How to validate input values with React?

Spread the love

To validate input values with React, we can use react-hook-form.

To install it, we run

npm i react-hook-form

Then we use it by writing

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

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

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input name="firstname" ref={register} />

      <input name="lastname" ref={register({ required: true })} />
      {errors.lastname && "Last name is required."}

      <input name="age" ref={register({ pattern: /\d+/ })} />
      {errors.age && "Please enter number for age."}

      <input type="submit" />
    </form>
  );
}

to call the useForm hook to return an object with a few properties we use.

Then we add a form element with the onSubmit prop set top handleSubmit(onSubmit).

We use handleSubmit to return a function that does form validation before calling onSubmit.

We call register to register form fields and add validation rules.

And we should errors using the errors property.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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