How can one pass req.validationErrors() from the backend to the frontend with Express Validator?

Hello and thank you for taking the time to read this. I am currently trying to implement express-validator in my project. It's working well as it blocks posts if, for example, the name input is empty. However, I'm struggling to display the error message on the front end despite trying various methods. If anyone could provide some guidance, I would greatly appreciate it. Apologies for the lengthy message. Here is a link to the express-validator documentation that might be helpful:

Here is a snippet of my code...

 <form id="sign-in">
      // Form fields go here
</section>

<footer>
</footer>
<script type="module" src="/js/sign-in.js"></script> 

Next, I have a fetch request in my sign-in.js file:

document.getElementById('sign-in').addEventListener('submit', event => { 
// Event handling logic

const name = document.getElementById('name').value
const username = document.getElementById('username').value
...

window.fetch(`${config.serverHost}/sign-in`, {
  method: 'post',
  body: JSON.stringify({
    name,
    username,
    ...
  })
}).then((res, errors) => {
  if (res.status === 200) {
    window.parent.location.reload()
  } else if (res.status === 422) {
    // Need help displaying error message here
  }
})

Lastly, on the server side:

app.post('/sign-in', (req, res, next) => {
// Express validator //
  
  // Validation checks
  
  const errors = req.validationErrors()

    if (errors) {
      // Need assistance with displaying error message
    } else {
      // Success message
    }  
  }) 

Answer №1

When working with your client, you have a couple of options available:

  1. You can opt to utilize either express-flash or connect-flash in order to transmit errors back to your view. Check out this post for more information on the distinctions between them.
  2. Alternatively, you can employ res.json to return the errors object that was generated from validationErrors(). Remember to specify the appropriate HTTP status code as well.

Answer №2

After finding the solution, I decided to share it in case it could benefit others who encounter a similar issue. Below is the content of the sign-in.js file:

.then(result => {
  if (result.status !== 200) {
    result.json()
    .then(result => errorMessages.innerHTML = result.map(item => `<p>${item.msg}</p>`).join(''))
  } else {
    window.parent.location.reload()
  }
})

In addition, here is the snippet of code for the server:

const errs = req.validationErrors()
  if (errs) {
    res.status(422).json(errs)
  } else {...}

A special thanks goes out to Francisco for providing assistance with this matter.

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

What steps are involved in setting up a Typescript-based custom Jest environment?

Currently, I am attempting to develop an extension based on jest-node-environment as a CustomTestEnvironment. However, I encountered an error when trying to execute jest: ● Test suite failed to run ~/git/my-application/tests/environment/custom-test ...

What could be causing the malfunction in my JavaScript random selector?

Can anyone assist me with this issue? I'm attempting to implement JavaScript functionality to highlight randomly selected picks that I input, but it's not functioning correctly. Every time I inspect my JS code on the webpage, I encounter an erro ...

Could it be that the AmCharts Drillup feature is not fully integrated with AngularJS?

UPDATE: Check out this Plunker I created to better showcase the issue. There seems to be an issue with the Back link label in the chart not functioning as expected. I'm currently facing a challenge with the AmCharts Drillup function, which should a ...

Utilizing a dynamic value in an Angular directive

For my latest project, I am working on developing a basic JSON pretty-printer directive using angular.js. Here is the code snippet I have so far: (function(_name) { function prettyJson() { return { restrict: 'E', ...

Discover the process of executing two functions simultaneously by interacting with a VRbutton through React360

As a newcomer to React, I am still learning the ropes and facing a challenge with using two functions simultaneously with Vrbutton (or any button) on onClick event. I have attempted various methods (referenced in my commented out code below) to make multi ...

Ways to emphasize the chosen row within angular js 4

Today, I am exploring an example to understand how data can be passed from a parent component to a child component and back. Below are the files that I have used for this example. I have included both the HTML and TypeScript files for both the parent and ...

Shifting Icon to the Right within the Drawer Navigator Toolbar

While modifying the example code for Material UI's drawer navigator, I decided to enhance it by adding a notification icon and a checkout icon with the Admin Panel typography in the toolbar. However, I encountered an issue where the checkout icon app ...

Tips for handling promise coverage within functions during unit testing with Jest

How can I ensure coverage for the resolve and reject functions of a promise within a function while conducting unit tests using Jest? You can refer to the code snippet below. Service.js export const userLogin = data => { return AjaxService.post( ...

Issue with Google Cloud Task failing to forward body data to an HTTP Cloud Function

I have a Google Cloud task where I took most of the code from the Cloud Tasks documentation. You can find the documentation here: https://cloud.google.com/tasks/docs/creating-http-target-tasks The purpose of the cloud function is to receive dateTo and dat ...

Unable to load circles on page refresh with amCharts Maps

I am experiencing an issue with the functionality of my amCharts maps. Whenever I refresh the page, the circles that are supposed to be displayed disappear. However, when I zoom in, the circles reappear. This problem has me puzzled, and I'm not sure ...

Is there an easier method to utilize ES6's property shorthand when passing an object in TypeScript, without needing to prefix arguments with interface names?

When working with JavaScript, I often find myself writing functions like the one below to utilize ES6's property shorthand feature: function exampleFunction({param1, param2}) { console.log(param1 + " " + param2); } //Usage: const param1 = "param1" ...

Tips for substituting commas and slashes within an input text box

For instance, if the input is "1,23/456", the output should be "123456". When "1,23/456" is entered into the input field and "enter" is pressed, it should automatically convert to "123456". <input id="Id" ng-model="Id" name="searchInput" type="text"&g ...

What is the best way to extract the ID of an element that triggers an OnChange event?

Just a heads up: The solution to my problem ended up being CSS code that was triggered by clicking on a widget. Once I realized it was CSS, along with the widget name and hover action, I was able to handle it successfully. Previous question before the PS ...

Utilizing a function from a library in an Object within a Typescript environment

Currently, I am working on assigning a field within my interface to a function from an external library in the following manner: import { Accelerometer, } from 'expo-sensors'; type SensorInterface = { permChecker: () => Promise<Permiss ...

Making a column in a Vue data grid return as a clickable button

My goal is to utilize vue.js grid to display multiple columns with calculated text values, along with a clickable column at the end that triggers a dynamic action based on a parameter (such as calling an API in Laravel). However, when I include the last c ...

Having trouble getting my asynchronous promise to work properly

I am currently working on implementing a login server function and I am struggling to understand why the promise I'm making is not being called. My setup involves using MongoDB with Mongoose as the backend, which is connected to using User.findOne. A ...

What is the most effective method for populating an array with all images from a particular directory?

I recently installed a pdf viewer plugin on my website (check it out here: ), and I have a question regarding its functionality. I am looking to include approximately 60 - 70 pages in this flip book, but I am unsure of how to proceed. I have attempted var ...

"Dilemma: Why won't the AJAX form post load inside the

Apologies for the simple question, but I'm experiencing an issue where nothing happens when the button is pressed. Any assistance would be greatly appreciated. AJAX $(document).on("ready", function(){ //Form action $("#wbForm").on("submit", function( ...

Extending a Typescript class from another file

I have a total of three classes spread across three separate .ts files - ClassA, ClassB, and ClassC. Firstly, in the initial file (file a.ts), I have: //file a.ts class ClassA { } The second file contains: //file b.ts export class ClassB extends Class ...

Include scrollView on smaller screens based on conditions

While incorporating an overlay in my application, how can I integrate a ScrollView specifically for smaller devices? Initially, I am checking the width: const windowWidth = Dimensions.get("window").width; Subsequently, I am attempting to display the Scro ...