DEV Community

Cover image for Authentication Using React-hook-form
Shivani tiwari
Shivani tiwari

Posted on

Authentication Using React-hook-form

Hey Everyone,

Today I discuss the REACT HOOK FORM it is easy to use for validating forms, shows the error message and you can easily update the form value as well

so there are some steps which you have to follow -

  1. you can also go through the official website of React Hook form here the link - https://react-hook-form.com/get-started

  2. Install the react hook form by using this link - https://www.npmjs.com/package/react-hook-form

  3. create your Login or signup form first

  4. then use the useForm() hook you can so this through the official website for this

Example-

import React from 'react'
import { createUserWithEmailAndPassword } from 'firebase/auth';
import { useForm } from 'react-hook-form';

const Register = ({ history }) => {
    const {
    handleSubmit,
    formState: { errors },
    trigger,
    register,
    watch
    } = useForm();

    async function onhandleSubmit(data) {
     //console.log(data)
        try {
        await createUserWithEmailAndPassword(
        auth, data.email, data.password, data.name)
        history.push("/");
        alert ("User Created Successfully")
        } catch (error) {
        console.log(error)
        alert ("User created failed")
        alert(error);
      }
    }

 return (
  <div>
    <Form onSubmit={handleSubmit(onhandleSubmit)}>
      <h5>Create an account</h5>
      <div>
        <div>
         <label>Your email address</label>
          <input
            id="email"
            name="email"
            type= 'email'
            required={true}
            {...register("email", {
            required: "Email is Required!!!" ,
            pattern: {
            value: /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i,
            message: "Invalid email address",
            }})}
            error={Boolean(errors.email)}
          ></input>
          {errors.email && (
          <small className="text-danger">{errors.email.message}</small>
          )}
        </div>
      <div>
        <label>Your password</label>
        <input
           name='password'
           id="password"
           type= 'password'
           autoComplete='off'
           className={`form-control ${errors.password && "invalid"}`}
           required={true}
           {...register("password", {
           required: "You must specify a password",
           pattern: {
           value: '^(?=.*?[A-Z])(?=(.*[a-z]){1,})(?=(.*[\d]){1,})(?=(.*[\W]){    1,})(?!.*\s).{8,}$',
           message: "Password should contain at least one number and one    special character"
           },
          minLength: {
          value: 8,
          message: "Password must be more than 8 characters"
          },
          maxLength: {
          value: 20,
          message: "Password must be less than 20 characters"
          },
          })}
        ></input>
          {errors.password && (
          <small className="text-danger">{errors.password.message}</small>
          )}
      </div>
      <div>
        <label>Confirm your password</label>
        <input
           id="confirmPassword"
           name="confirmPassword"
           type='password'
           {...register( 'confirmPassword', {
           validate: value =>
           value === watch("password", "") || "The passwords do not match"
           })}
           autoComplete='off'
           onPaste={(e) =>{
           e.preventDefault();
           return false
           }}
           error={Boolean(errors.confirmPassword)}
           className={`form-control ${errors.confirmPassword && "invalid"}`}
           required={true}
         />
           {errors.confirmPassword && (
           <small className="text-danger">{errors.confirmPassword.message}    </small>
           )}
      </div>
      <div>
        <label>Your full name</label>
        <input
           name='name'
           type="name"
           className={`form-control ${errors.name && "invalid"}`}
           required={true}
           defaultValue=""
          {...register("name", { required: "Fullname is Required!!!" })}
          {errors.name && (
          <small className="text-danger">Fullname is Required!!!</small>
         )}
        </div>
        <div>
          <button>Create an account</button>
        </div>
      </div>
    </Form>
  </div>
)}
export default withRouter(Register)

Enter fullscreen mode Exit fullscreen mode

here is the example please go through and if you like this article like my article and follow for more updates

Top comments (0)