Struggling with making react-hook-form correctly validate an email address

I've been struggling for a long time to make this validation work correctly, but it seems impossible. I even added some text at the bottom to display an error message related to the email, but it always shows no error, regardless of the situation.

Edit: Sandbox link - https://codesandbox.io/s/damp-star-8gv3l

This is the input section:

           <div>
              <label
                htmlFor="email"
                className="block text-sm font-medium text-gray-700"
              >
                Email address
              </label>
              <div className="mt-1">
                <input
                  {...register("email", {
                    required: {
                      value: true,
                      message: "Please enter your email address",
                    },
                    pattern: {
                      value:
                        /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,
                      message: "Invalid email address",
                    },
                  })}
                  id="email"
                  name="email"
                  type="email"
                  autoComplete="off"
                  className={`input w-full ${
                    !errors.email && dirtyFields.email && "!bg-green-50"
                  }`}
                />

              {errors.email ? "error" : "no error"}
              {errors.email?.message && (
                <ErrorMessage>{errors.email?.message}</ErrorMessage>
              )}
            </div>

And here is my hook setup:

  const {
    register,
    watch,
    control,
    formState: { errors, isValid, dirtyFields },
  } = useForm<SignupProps>({
    defaultValues: {
      email: "",
      password: "",
      confirmPassword: "",
      username: "",
      firstName: "",
      surname: "",
      isShop: false,
    },
  });

Answer №1

Based on your codesandbox, here is a list of modifications you need to make:

  • Include <form /> tag in your code
  • Add mode: 'onChange' in the options for useForm to show errors while typing in the input field
  • If you wish to trigger validation upon submission, include a submit button
  • Show any error message that is returned from the validation process

View the updated codesandbox at: https://codesandbox.io/s/autumn-sea-ps37x?file=/pages/index.js

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The onclick event for a Bootstrap .btn-group checkbox functions correctly in JSFiddle, but encounters issues when tested

The toggle button group in the form below utilizes Bootstrap and checkboxes. I am looking to track click events on the checkbox inputs. <html> <head> <title>Example: Bootstrap toggle button group</title> <meta charset="UTF-8 ...

Guide to displaying all files from firebase storage on a screen

I'm struggling to display all the files from my firebase storage. I've tried pushing them into an array, but I can only get one file name. Any ideas on how to push all the files into the fileName array? function Home() { const [fileURL, setFile ...

Issue with calling function from props in React is not being resolved

There seems to be an issue with the function not being called when passed into a functional component. While the onSubmit function is triggered, the login(email, password) function inside the Login component is never executed. Despite placing console.log s ...

Can the Route be modified in Next.js?

I have developed search functionality that navigates to "/search/xxxx", but it is located in the header. Every time I perform a search, the route gets repeated and becomes "/search/search/xxx". Could you suggest any way other than usin ...

React Drawer triggering excessive re-renders

I am trying to implement a button that, when clicked, will display a Drawer from the bottom. Here is the code snippet I have written: import * as React from "react"; import Box from "@mui/material/Box"; import Drawer from "@mui/mat ...

Showing or hiding child content based on the selected state of a radio button

This is a follow-up question from a previous one on changing check boxes to radio buttons. Now, I need to display child radio buttons and change the background color when the parent radio button is active. The child radio buttons should be hidden and the b ...

IBM Watson Conversation and Angular Integration

After recently diving into Angular, I am eager to incorporate a Watson conversation bot into my angular module. Unfortunately, I'm facing an issue with including a library in Angular. To retrieve the Watson answer, I am utilizing botkit-middleware-wat ...

Is it possible to extract the body from the post request using req.body.item?

After working with Express, I learned how to extract body data from a post request. Most examples showed that using req.body.item should retrieve the desired value for tasks like inserting into a table. However, in my case, I found that I couldn't ac ...

Get the game using electron / determine the game's version via electron

I'm currently working on creating a game launcher using electron. There are two main questions that I have: What is the best method for downloading files from the client (specifically in AngularJS)? FTP or HTTP? How can I implement a system to detect ...

What is the best way to include an "average" line in a nvd3.js Stacked Area Chart?

My Stacked Area Chart is up and running smoothly using NVD3.js. You can view it in action on this working jsfiddle link. var volumeData = [{"key":"Hit","values":[[1.3781628E12,12],[1.3782492E12,9],[1.3783356E12,9],[1.378422E12,4],[1.3785084E12,2],[1.37859 ...

Getting the specific nested array of objects element using filter in Angular - demystified!

I've been attempting to filter the nested array of objects and showcase the details when the min_age_limit===18. The JSON data is as follows: "centers": [ { "center_id": 603425, "name" ...

"Incorporate multiple data entries into a table with the help of Jquery

How can I store multiple values in a table row using jQuery or JavaScript when the values come from a database via Ajax? <html> <head> <style> table { font-family: arial, sans-serif; border-collapse: collapse; width: 100%; } td, th ...

Issue with Angular ng-model not functioning as expected within ng-repeat block

Encountering an issue when trying to bind Json data into ng-model within ng-repeat. html : <div ng-controller="Ctrl"> <div> <table> <th> <td>add</td> <td>ed ...

Submitting a form with AJAX and additional fields can be accomplished by including the extra fields in

Imagine a scenario where I am working with a basic form like the one below <%= form_for(@category) do |f| %> <% if @category.errors.any? %> <div id="error_explanation"> <h2><%= pluralize(@category.errors.count, "erro ...

Tips for maintaining the data on a page continuously updating in AngularJS

I have this code snippet: $cookieStore.put('profileData', $scope.profileData); var profileData = $cookieStore.get('profileData'); $scope.init = function(){ var profileData = $cookieStore.get('pr ...

Looping through a set of API calls using JavaScript Web API

Currently, I am in the process of developing an application using angularjs and ionic. Within this app, I have an array containing IDs, and my objective is to retrieve their corresponding names. To achieve this, I attempted the following code snippet: var ...

I'm stuck trying to figure out all the parameters for the MapsPage component in Angular 2

Currently, I am utilizing Angular2 with Ionic2 for my mobile app development. Everything was working flawlessly until I decided to incorporate a new module for Google Maps navigation. Specifically, I am using phonegap-launch-navigator for this purpose. The ...

Issue with form array patching causing value not to be set on material multiple select

When attempting to populate a mat-select with multiple options using an array of ids from Firestore, I encountered an issue. The approach involved looping through the array, creating a new form control for each id, and then adding it to the formArray using ...

Implementing Material UI datetime-local feature with no minute selection

Is there a way to hide minutes in a TextField with type = datetime-local? <TextField label="From" type="datetime-local" InputLabelProps={{ shrink: true, }} /> This is how it appears on my end: screenshot ...

As soon as I hit the submit button on my website form, the URL is automatically refreshed with the information I provided

I am a beginner when it comes to forms and recently copied and pasted this login snippet code: <div class="login-form-1"> <form id="login-form" class="text-left"> <div class="main-login-form"> <div class="login-group"> ...