Form Validation Library | React | 1
Tags: html, javascript, react, webdev
Published: 2023-10-12 13:50:46

Hello Everyone, today i am here with another series for Form Handling and validations.We will cover many topics and use cases and libraries as well to make our work easy pease.

Let's get started...
## Technologies and Libraries Used 
* HTML and CSS
* JavaScript
* Tailwind ( CSS Framework)
* React JS
* React hooks form ( Form handling library)
* Yup (Validation library)

## Introduction to React Hooks Form
* Before user input is processed or saved by an application, form validation is the process of making sure it complies with the standards and criteria stated. Form validation verifies if user-provided data is legitimate and acceptable when a user interacts with a web form, for as by filling out fields in a registration form or sending payment information.
* For the development of dependable, user-friendly, secure, and compliant online applications, form validations and error handling are crucial. They guarantee the proper operation of your application, a great user experience, and the security and integrity of your data.

## What is React hooks form?
* For React apps, React Hook Form is a well-liked and compact form validation library. It has a number of features that make managing forms easier.

Some key features of react hooks form.
* Speed and simplicity: React Hook Form doesn't rely on re-rendering the component tree and embraces React's unidirectional data flow, which improves speed.
* Simple API: React Hook Form has a simple API that makes it simple to understand and use. The useForm hook is the major focal point.
* React Hook Form minimizes re-renders by only updating the components connected to the fields being modified.
Support for Validation Schemas: Allows interaction with a number of validation libraries, including Yup and Jod, to define validation schemas.
* Async Validation Support, Conditional Validation, Dynamic Forms and Fields, and others.

## Basic Form Handling-
### Creating a hook for the form and submit method
```js
import { useForm } from "react-hook-form"
.
.
const Form = () => {
    // Destructuring methods from hook
    const { register, handleSubmit, setValue, getValues, reset, watch } = useForm({
        // assigning initial values 
        defaultValues:{
            name:"",
            email:"",
        },
    })

// Submit handler method with reset method
const submitHandler = values => {
   console.log(values)
   reset()
}

// Setter and getter methods for inputs
useEffect(() => {
  setValue("name","Ironman")

  const name = getValues("name")
  console.log(name)
}, [])

// Watching input values with watch method
const details = watch()
console.log(details)

  return (
     //jsx
   )
}

export default Form
```
* Firstly we have imported the useForm hook, which has many inbuilt methods to use for the form handling. We have passed 1 object to the useForm hooks, this will be the default values for our form input fields, initially empty strings
* Then we have destructured few methods from the useForm hook

1. register - it is used to register an input element to the useForm, so it will have access to its methods and objects.
2. handleSubmit - it is used to handle the form submit method, it takes 1 parameter which is the submit handler method itself
3. setValue - it is used to manually set a particular input field value
4. getValue - it is used to get an input field value or all the input fields value in a json format.
5. reset - it is used to reset the form input values.
6. watch - it is used to dynamically watch the input fields value

* We are resetting the form on form submit. Also we are use setting and getting the name input field inside useEffect.
* Then we have used a variable details to attach the watch method, without any parameters, it will show all the input fields value in a json format.

### JSX
```js
  <div className='grid-container'>
        <form className='form-container' onSubmit={handleSubmit(submitHandler)}>
            <div className='form-control'>
                <label htmlFor="name">Name</label>
                <div className='relative'>
                    <input type='text' id="name" className={`form-input`} {...register("name")} />
                </div>
            </div>
            <div className='form-control'>
               <label htmlFor="email">Email</label>
               <div className='relative'>
                  <input type='email' id="email" className={`form-input`} {...register("email")} />
                </div>
           </div>
          <button type="submit" className="form-submit">Submit</button>
      </form>
 </div>
```
* Here we have created 2 inputs fields and then spread the register method so all its properties and methods will be accessible to the input field, it takes 1 parameter which is the unique name of the input field, after rendering this unique name will be the "name" attribute for the input field.
* handleSubmit is passed with the submitHandler method as its parameter to the onSubmit event handlers. It will automatically pass down the values and other data to the submitHandler method.


That's it for the first blog in this series

Feel free to give suggestions in comments to improve the component and make it more reusable and efficient.
THANK YOU FOR CHECKING THIS POST
You can contact me on -
Instagram - https://www.instagram.com/supremacism__shubh/
LinkedIn - https://www.linkedin.com/in/shubham-tiwari-b7544b193/
Email - shubhmtiwri00@gmail.com

#### You can help me with some donation at the link below Thank you👇👇
☕ --> https://www.buymeacoffee.com/waaduheck <--

Also check these posts as well

{% link https://dev.to/shubhamtiwari909/css-trigonometry-circle-3bl3 %}
{% link https://dev.to/shubhamtiwari909/next-js-multistep-form-2gc9 %}
{% link https://dev.to/shubhamtiwari909/react-components-gallary-3p7b %}
{% link https://dev.to/shubhamtiwari909/react-interactive-components-tabs-48fh %}