A helpful guide on displaying validation errors in a form using React JS

After creating a form and connecting it to the server, I encountered an issue with displaying validation errors below respective input fields. The error message response in case of validation error is as follows: "message": "ValidationError: confirmPassword: Confirm Password did not match". Using regular expressions, I can extract the error message "Confirm password did not match" from this response.


<form>
        <h2>Create Account</h2>

        <fieldset>
          <label for="name">Username</label>
          <input
            onChange={(e) => handle(e)}
            value={data.name}
            type="text"
            id="name"
            name="name"
          />

          <label for="email">Email</label>
          <input
            onChange={(e) => handle(e)}
            value={data.email}
            type="email"
            id="email"
            name="email"
          />

          <label for="password">Password</label>
          <input
            onChange={(e) => handle(e)}
            value={data.password}
            type="text"
            id="password"
            name="password"
          />
          <label for="confirmPassword">Confirm Password</label>
          <input
            onChange={(e) => handle(e)}
            value={data.confirmPassword}
            type="text"
            id="confirmPassword"
            name="confirmPassword"
          />
        </fieldset>
        <button type="submit" onClick={(e) => sendData(e)}>
          Create Account
        </button>
      </form>

I am seeking a solution on how to properly display this error message below the respective input field within the form structure.

Answer №1

  1. Ensure to implement the validation function within the reducer
const reducer = combineReducers({
  form: formReducer.validation({
    loginValidation: loginValidation,
  })
})

const loginValidation = values => {
  const errors = {}
  if (!values.email) {
    errors.email = 'Please enter your email'
  } else if (!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(values.email)) {
    errors.email = 'Invalid email format'
  }

  if (!values.password) {
    errors.age = 'Password is required'
  }

  if (!values.confirmPassword) {
    errors.age = 'Confirm password is required'
  }

  if (values.confirmPassword !== values.password) {
    errors.age = 'Passwords do not match'
  } 
  return errors
}
  1. When working on the form component, follow these steps:
<div>
  <label>Email</label>
  <Field name="email" component={email =>
     <div>
      <input type="text" {...email} placeholder="Enter Email"/>
      {email.touched && email.error && <span>{email.error}</span>}
     </div>
    }/>
      </div>

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 Google Drive API in Node.js is notifying the deletion of files

I encountered an issue with the Google Drive API in my application. Even after deleting files from Google Drive, the listfiles function still returns those deleted files. Is there a solution to prevent this from happening? Below is the function of my API: ...

The absence of a label or div element on a JavaScript checkbox change event is causing issues

Currently, I am constructing a webpage utilizing ASP.NET web forms in combination with JavaScript and jQuery. The main objective is to create a functionality for a checkbox that reacts to a change event as follows: when the checkbox is checked, display thr ...

Using CSS to align and place elements

Currently facing a challenge with my HTML/CSS code regarding the horizontal centering of two divs (A, B) within one absolutely positioned div (C) that contains background images. Key aspects to consider: The bottom edge of the larger div (A) should alig ...

Trouble arises when attempting to create a two-column layout using Material UI's <Grid> component

My goal is to create a two-column layout where each column takes up half of the screen and has equal height. To better illustrate, take a look at this image. The code I've tried so far is not working as expected: import React from "react"; import { ...

"Unleashing the power of React Native: A single button that reveals three different names

I have a piece of code that changes the name of a button from (KEYWORD) to a different one (KEYNOS) each time it is clicked. How can I modify it to change to a third value (KEYCH), where the default name is (A, B, C... etc), the first click shows Numbers ...

Numerous classifications and tags available for c3-angular-directive-c3 charts

I have a project requirement to create a stacked bar chart that should look like the image below: https://i.sstatic.net/MBwXy.png Currently, I am utilizing the c3-angular-directive library along with c3.js for chart creation. The challenge lies in dealin ...

AWS Amplify: The useAuthenticator hook does not trigger a re-render when there is a change in the user.attributes field

In my React project, I am utilizing Amplify with versions "@aws-amplify/ui-react": "^2.17.1" and "aws-amplify": "^4.3.22", but I have encountered unexpected behavior. When importing { useAuthenticator } from '@aws-amplify/ui-react'; into my comp ...

Ways to resolve the issue of being unable to retrieve data using jQuery

My code is working, but I am facing a little annoying problem that I can't solve on my own. The problem is that I can only retrieve the first record (id) from my data grid, but I can't retrieve the second or any other record id. For example: W ...

How can we prevent excessive hook calls when utilizing components in React?

I've run into an issue with the modal component hook I created below. I want to set up this modal at the app level so that I can easily access it via a global state like Zustand whenever necessary. Here is the structure of the modal component: Crea ...

What is the process of displaying JSON headers using JavaScript?

Although it may seem like a simple question, I am new to JSON. Can someone explain how to display a heading in the console? This is the code I have: var jsonstr = '{"profile":{"name" : "raj","age":"35&qu ...

Streamline your processes by automating jQuery AJAX forms

I am looking to automate a click function using the code snippet below in order to directly submit form votes. Is there a method to develop a standalone script that can submit the votes without requiring a webpage refresh: <input type="submit" id="edit ...

The structure of the figure tag for HTML5 validation

Could you please confirm if the Figure tag is correctly used in the html structure? Regarding html5 validation, can I use this structure? <a href="#"> <figure> <img src="" class="img-responsive" alt=""> <figcaption> ...

Utilize AngularJS ng-repeat directive to refine JSON objects

I'm working on an angular js controller with a json array that organizes countries by continents. Each continent consists of its own array of countries. //CONTROLLER app.controller('CountryController', function(){ this.continents = ...

Exploring the array mapping technique in React with nested objects

As part of a school project, I am working on creating a dashboard to visualize some data. I have successfully loaded the data into the front end using React. Now my goal is to retrieve specific values from a large array. However, I am uncertain about how ...

What is the process to retrieve a variable from a Node.js file in an HTML document?

What is the best way to showcase a variable from a node.js route in an HTML File? I have a node.js route structure as follows: router.post("/login", async (req,res) => { try { const formData = req.body const name = formData.name ...

Is iOS Safari automatically filling all fields with identical information?

I'm in the process of creating a basic form that allows users to input their name/email and their friend's name/email. The code snippet can be found below. Interestingly, while most browsers autofill only the first two fields, iOS Safari on my i ...

Can a time input validation be implemented in a text field using only React?

To ensure input data is checked within a specific time range, we can use multiple input fields for each time unit to improve visualization. (Instead of using a single input field, separate inputs are used for different time units for better clarity) http ...

Show different text or letter when hovering

Is there a way to hide one letter and display another in a link, with a different style on hover? For example: This is a... ...regular link. And this is a... ...hovered link. Any ideas on how to make this happen? Thank you. Edit: Just to clarify — ...

Restarting a timer with React useEffect

I've been experimenting with the useEffect hook and encountered a problem that has me stumped. My simple counter example uses setTimeout inside useEffect to update values. if (countState.stopWatch === 0) { dispatch({ type: 'reset' }); ...

Angular keeps throwing an error saying "Provider not found" when trying to inject a factory

Issue: Encountering an Unknown Provider Error in Angular App for: UnitProvider <- Unit Error Details: Error: [$injector:unpr] Unknown provider: UnitProvider <- Unit Codepen Link: View LIVE CODE Example I recently came across a fascinating vide ...