Having trouble retrieving a specific object from an array using EJS

When re-rendering my form with any errors, I am able to display the errors in a list. However, I would like to access each error individually to display them under the invalid input instead of all at the bottom of the form.

Here is what I have tried so far:

// controller.js

(req, res, next) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      res.render("quotes", {
        form: req.body,
        errors: errors.array()
      });
      return;
    } 
// ejs file

 <% if (locals.errors) { %>

       <ul>

          <% errors.forEach(error => { %>
          <li><%= error.msg %></li>
          <% }) %>

        </ul>
  <% } %>



However, this solution displays all errors in a list format rather than individually under each invalid input. Below is my attempt to show errors individually:

//controller.js

(req, res, next) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      res.render("quotes", {
        form: req.body,
        errors: errors.array(),
        error1: errors.array()[0].msg,
        error2: errors.array()[1].msg,
        error3: errors.array()[2].msg
      });
      return;
    }

// ejs file

<% if (locals.errors) { %> <li> <%= error1 %></li> <% } %>


errors: [
    {
      value: '',
      msg: 'First name must be specified',
      param: 'firstName',
      location: 'body'
    },
    {
      value: '',
      msg: 'Last name must be specified',
      param: 'lastName',
      location: 'body'
    },
    {
      value: '',
      msg: 'Please enter a valid email',
      param: 'email',
      location: 'body'
    }
  ] 

Any guidance or suggestions on how to achieve displaying errors individually under each invalid input would be greatly appreciated!

Answer №1

any assistance would be greatly appreciated!

Alright, here is my proposal.

It is important to correctly associate each error with the corresponding input field. To achieve this, consider restructuring the errors object (array) like so:

let errors = {
    'firstName': {
      value: '',
      msg: 'Please provide a first name',
      location: 'body'
    },
    'lastName': {
      value: '',
      msg: 'Please specify a last name',
      location: 'body'
    },
    'email': {
      value: '',
      msg: 'Ensure you enter a valid email address',
      location: 'body'
    }
};

Now, your errors object contains keys (if there are no errors, then let errors = {}).

This enables you to assign an error message to any input field:

<% if (locals.errors && errors.firstName) { %> <div class="error"><%= errors.firstName.msg %></div> <% } %>
<input type="text" id="firstName" name="firstName"/>

<% if (locals.errors && errors.lastName) { %> <div class="error"><%= errors.lastName.msg %></div> <% } %>
<input type="text" id="lastName" name="lastName"/>

If you need to convert your errors array into an object, you can follow this approach:

let errorsObj = {};
errors.map((item) => {
  const id = item.param;
  delete item.param;
  errorsObj[id] = item;
});

Execute the above code at the point where you have your errors array, but before rendering it to the page. Consequently, utilize errorsObj instead of errors:

<% if (locals.errors && errorsObj.firstName) { %> <div class="error"><%= errorsObj.firstName.msg %></div> <% } %>
<input type="text" id="firstName" name="firstName"/>

Answer №2

Here is a quick solution:

//controller.js

(req, res, next) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      res.render("quotes", {
        form: req.body,
        errors: errors.array()
        error1: errors.array()[0] && errors.array()[0].msg,
        error2: errors.array()[1] && errors.array()[1].msg,
        error3: errors.array()[2] && errors.array()[2].msg,
      });
      return;
    } 

Don't forget to check out lodash

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 mystery of the Accordion Effect: A Next.js/React.js issue where it slides up but refuses to

After implementing a custom accordion using next.js, I encountered an issue where the slide animation worked successfully when moving up and out upon clicking the button. However, when trying to move it back down into the content, it did not animate as exp ...

Obtaining data from an external ng-repeat element

My list contains items that are being repeated using ng-repeat details. I want to be able to hover over one of the li elements and have the background of a div called background (which is outside of the ng-repeat) change to the url of the corresponding d ...

Error 405: Javascript page redirection leads to Method Not Allowed issue

After receiving the result from the ajax success method, I am facing an issue where the redirection to another page is being blocked and displaying the following error: Page 405 Method Not Allowed I am seeking suggestions on how to fix this as I need to ...

Angular UI-Router has a quirk where it may execute a controller twice upon loading if it is defined within the

Every time I run the code in my controller, it seems to be executed twice, resulting in duplicate outputs in the console.log window of Chrome Dev Tools. questions.html <div ng-controller="questionController as vm"> </div> questionController. ...

The chart JS label callback requires a specified type declaration

Currently, I am in the process of updating an old Angular platform to a newer version. One requirement is that everything must have its type declaration. I encountered a problem with the label callback showing this error: The error message reads: "Type &a ...

Is it possible to pre-select a value in a PrimeVue Dropdown component?

Situation: Currently, I am incorporating PrimeVue into a Vue.js project. Within this setup, there is a dropdown component sourced from PrimeVue, utilizing an array of objects. The structure of the dropdown component appears as follows: <template #positi ...

Mastering the art of redirection in Node.js

Encountering an issue with redirecting between directories - having trouble directing to another file in a different directory. Here is my directory structure: -views -add_user.jade -routes -index.js Attempting to redirect to add_user.jade from inde ...

What causes an error when attempting to add a new user to the database?

Currently, I am delving into the world of Mongodb. To kick things off, I initiated by executing npm install --save mongoose uuid within the confines of Terminal. The primary objective of my project revolves around storing user information in the database. ...

Tips for retrieving data from a Mongoose query

Currently, I am tackling a registration task that involves server side validation before storing the data in mongo. Despite being new to mongoose, I am facing difficulties when it comes to returning data for completing the entire registration process. In ...

What could be preventing me from successfully calling the JavaScript AJAX function in this particular situation?

Here is my code snippet from a smarty template: <form name="transaction_form" id="transaction_form"> <table class="trnsction_details" width="100%" cellpadding="5" > <tbody> <tr> ...

When using jQuery and Laravel, why does the element not appear when setting its display to block after receiving a response?

Trying to handle data (id) retrieved from the database and stored in a button, which appears in a modal like this: There are buttons for "Add" and "Remove", but the "Remove" button is hidden. What I want to achieve: When the user clicks on the "Add" but ...

Update: Cannot mark as invalid a nested document that has not been included in an array

I recently encountered an issue with my upsert query in mongoose. It was functioning perfectly in version 3.8, but ever since I upgraded to version 4, I've been facing the following error: Unable to invalidate a subdocument that has not been added to ...

Injecting CSS styles into dynamically inserted DOM elements

Utilizing Javascript, I am injecting several DOM elements into the page. Currently, I can successfully inject a single DOM element and apply CSS styling to it: var $e = $('<div id="header"></div>'); $('body').append($e); $ ...

Tips for populating category and subcategory using JSON data

When creating an admin form in React, I want to have a Category and sub-category dropdown selection with options populated from a JSON file (categories.json). The respective sub-categories should be displayed based on the selected category while adding a n ...

Implementing user authentication in node.js with passport

Having trouble with a basic login system using passport. I keep getting an error when logging in with the correct credentials: Error: Express 500 TypeError - Cannot read property 'passport' of undefined Oddly enough, everything works fine when ...

Vue.js is like the modern version of jquery-cron

Is there a similar tool to jquery-cron with an easy-to-use text/select interface that anyone knows of? I've come across vue-cron and point-vue-cron, but they seem too complicated for my needs. ...

I am looking to gather user input in JavaScript and then showcase that input on the webpage. What would be the best

I am currently learning Java and I decided to challenge myself by creating a hangman game. The issue I am facing is that when the user inputs a letter, nothing happens - there is no output indicating whether the guess was correct or incorrect. I suspect th ...

React Nextjs implementation of a fixed navigation bar to stick at the top

Hello, I am experiencing some issues setting up a sticky navbar in Next.js. The current navbar doesn't seem to be functioning as expected. Is there anyone who can assist me with the code provided below? import React, { useEffect } from 'react&apo ...

The Angular directive was unable to reach the controller located higher up in the DOM hierarchy

template <section id="content" ng-controller="ReservationController as resvnCtrl" > <form role="form" name="resvnCtrl.form"> <div data-date-picker> </div> ...

The function was triggered upon the form loading, instead of being activated when the button was clicked

The issue I am facing is that in the code snippet below, the function readCSV() is not being triggered when buttons for filepath1 and filepath2 are clicked. The function is only executed on form load. I was expecting it to work on button click as well. I ...