React Hook Form that can simplify form validation

How to setup form validation using React-Hook-Form


In search of a perfect and simple form validation library I found two. It is so easy to get thing done with Formik, but there is also a plan B which simpler than I think.

React Hook Form

This is another form validation library for React developers to make interative forms with ease. The getStarted guide so simple to follow.

Dependency

npm install react-hook-form

We can destructure register, handleSubmit from the useForm hook.

const { register, handleSubmit } = useForm();

Register

The register can be used to register the input. Validation can be passed as the second parameter the register function.

 <input {...register("exampleRequired", { required: true })} />

It can be a complex validation as follows

<input {...register("firstName", { required: true, maxLength: 20 })} />
      <input {...register("lastName", { pattern: /^[A-Za-z]+$/i })} />
      <input type="number" {...register("age", { min: 18, max: 99 })} />

handleSubmit

This can be used to implement our submit logic function

The complete sample

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

export default function App() {
  const { register, handleSubmit } = useForm();
  const onSubmit = data => console.log(data);
   
  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input {...register("firstName", { required: true, maxLength: 20 })} />
      <input {...register("lastName", { pattern: /^[A-Za-z]+$/i })} />
      <input type="number" {...register("age", { min: 18, max: 99 })} />
      <input type="submit" />
    </form>
  );
}

So I can focus on another component , no worries about Forms and validation

Author: Manoj

Developer and a self-learner, love to work with Reactjs, Angular, Node, Python and C#.Net

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.