React Hook Form Validation and Submit Example

Hello react devs, in this example i will show you react hook form validation example with form submit. In this react hook form validation example i will simply create a react functional component form and will validate it using react hook form package and then submit it with the form data.

So from this tutorial you will learn how to create and use react hook form package and submit data by using this react hook form package. So if you don't know how to use this package then this tutorial is for you. I will show you also react hook form package validation with ErrorMessage component from react hook form.

In the first step you need to install react hook form package by running below command:

npm i react-hook-form


Now we have to handle our error message, So we need a simple component to render associated input's error message. Run below command to install this error message showning component:

npm install @hookform/error-message


Now see the example code of react hook form validation example and form submit example:

import React from "react";
import { useForm } from "react-hook-form";
import { ErrorMessage } from '@hookform/error-message';

function App() {
  const { register, formState: {errors}, handleSubmit } = useForm();

  const onSubmit = (data) => {

  return (
      < form onSubmit={handleSubmit(onSubmit)} >
        < input name="firstName"
          {...register("firstName", {
            required: "required",
          })} / >
        < ErrorMessage errors={errors} name="firstName" / >

        < input name="lastName" 
          {...register("lastName", {
            required: "required",
          })} / >
        < ErrorMessage errors={errors} name="lastName" / >

        < input name="age" 
          {...register("age", {
            required: "required",
          })} / >
        < ErrorMessage errors={errors} name="age" / >

        < input type="submit" / >

export default App;


age: "2"
firstName: "CodeCheef"
lastName: "Is Awesome"
__proto__: Object


Read also: React Form Validation and Submit Example with Formik


Hope it can help you.


Facebook Github
A web enthusiastic, a self-motivated full-stack software engineer from Dhaka, Bangladesh with experience in developing applications using Laravel , React and Vue js