Specialized express Validator for 2 particular fields

I currently have 2 custom validators set up for the fields email and phone.

check('phone')
      .not()
      .isEmpty()
      .withMessage('Phone should not be empty')
      .custom(async phone => {
        const phoneCheck = await User.findOne({ phone: phone });
        if (phoneCheck !== null) {
          return Promise.reject();
        }
      }).withMessage('Phone is already in use.')

The validation for phone seems to be working fine without throwing any errors. However, the validation for email is causing an error on the browser.

check('email')
    .not()
    .isEmpty()
    .withMessage('Email should not be empty')
    .isEmail()
    .withMessage('Email must be valid')
    .custom(async email => {
      const emailCheck = await User.findOne({ email: email });
      if (emailCheck !== null) {
        return Promise.reject();
      }
    }).withMessage('Email is already in use.')

Interestingly, when testing the API in Postman, both errors are thrown for the phone validation.

This is how I am handling errors in my API function:

const errors = validationResult(req);
  if (!errors.isEmpty()) {
    const erroredFields = errors.array();
    const newErrors = erroredFields.map(err => {
      return {
        field: {
          name: err.param,
          error: err.msg
        }
      }
    })
    res.status(401).json({
      message: 'Validation Error',
      errors: newErrors
    })
  }

Results from the browser:

Results from Postman:

Both inputs produce the same output.

I am using Nuxt with Express. Is there something wrong with how I am implementing custom validations?

Answer №1

The issue actually didn't stem from express-validator. It turned out to be related to the usage of the vue-tel-input component for handling phone numbers. The component was inadvertently adding white spaces during formatting, causing the phone number to be submitted in an incorrect format. By using the .replace(/\s+/g, "") method, I successfully removed the white spaces and resolved the validation problem.

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

Exploring the varying treatment of the noscript tag across different web browsers

I've been searching everywhere, but I can't find any information on this topic. What I really want to understand is what browsers do with the content inside a noscript tag when JavaScript is enabled. Let's consider an example: According t ...

How can you use Vue.js @mouseover to target a specific <path> element within an <svg>?

Check out this Codepen example. I am working with an SVG map that contains various paths holding data. My goal is to retrieve the state name when hovering over a specific path. Currently, I have added an event listener to the svg element and am trying to ...

Rendering in ExpressJs after performing an action

Recently, I've been experimenting with ExpressJs and encountered an issue. var mysql = require('mysql'); var url = require('url'); var connection = mysql.createConnection({ host : 'localhost', port : &ap ...

How can I resolve the "AngularJS 1.6.6 component controller not registered" error plaguing my application?

I am currently using AngularJS version 1.6.6 along with Gulp for my project. Here are the snippets of my code, particularly focusing on the AppLayout component: /// app-layout.component.js angular.module('app').component('appLayout&ap ...

Encountering issues with NPM as it attempts to install a x64 dependency on a machine with an

I recently set up Nuxt 3 on my x64 PC without making any changes beyond the initial setup. If you're interested, here's the Git repository. However, I encountered an issue when trying to clone this setup onto my M1 MacBook. The installation proc ...

Issues concerning date and time manipulation - Library Moment.js

As a beginner in JavaScript, I've been working on an activity that generates a table of train times based on user input. However, I'm facing issues with formatting the arrival time correctly. Whenever I input the arrival time in military format ( ...

An error will be thrown if you try to pass an array attribute of an object as a prop to a React component

I'm trying to grasp why passing an array attribute of a data object into a Component as a prop is causing issues. Is this due to my understanding of how React functions, or are there potential pitfalls in this scenario? Any insight would be greatly ap ...

.toggle function malfunctioning

Upon page load, I have a script that toggles the County menu. The goal is to hide the county menu if any country other than "United Kingdom" is selected on page load. If the user selects another country after the page has loaded, there is an issue where ...

In Node.js with Express, ensure variable scope is restricted to the current request

In my express application, I have a feature that makes POST requests and calls different APIs. What I want to achieve is sending an email when any of the API requests result in an error. Here's a simplified version of what I'm working on: In the ...

How can I ensure that the AppBar background color matches the color of the navigation bar?

Having trouble changing the background color of the <AppBar> in my project. Using the Container component to set a maximum screen size, but encountering issues when the screen exceeds this limit. The AppBar background color appears as expected while ...

When attempting to display a sub view in Express, a 404 error is encountered

I am currently working with express and jade to display a web page. My intention is to render the page using this format 'http://127.0.0.1:5000/services/landfreight' but I keep encountering a 404 error. router.get('/service/landfreight' ...

Guide on how to trigger the opening of a side panel with a button click in Vue.js

Embarking on my first Vue app development journey, I find myself in need of guidance on how to trigger the opening of a panel by clicking a button within the header. Starting off with a simple HTML template, my goal is to add some interactivity upon click ...

Add the hue value from Hue into the Chromajs HSL state value

My objective is to dynamically change the background color of a div based on user input. I plan to assign the user's input as the value of the state key hue, and then set another state key called color to hold the HSL representation of the hue using C ...

What steps should I take to enable a route guard to authenticate a token once it has been stored in local storage?

I'm currently working on a basic login page with authentication using Angular and Express. Here's what I've got so far: a login component a service that handles http requests and stores the jwt token in local storage a route guard for the ...

Developing tests for an asynchronous function

I recently encountered a bug in my AWS Lambda code written in NodeJS 6.10 that caused me two sleepless nights. I didn't conduct integration testing, relying solely on unit tests, which led to the oversight. After inserting return workerCallback(err);, ...

How to Retrieve Content from an iFrame Using jQuery?

I am facing a challenge with an HTML form that is directed to an IFRAME upon clicking "submit". The iframe then loads a page after the submission, which indicates whether the user-input data is valid or not. It simply displays on screen as "TRUE" or "FALSE ...

Is d3 Version pretending to be a superior version?

I have encountered an issue with my project that involved using d3 v5.5.0. After transferring it to a different computer and running npm install, the application now seems to be recognizing d3 as a higher version? A crucial part of my program relies on th ...

Select an image based on the input value provided

I'm new to coding and I'm attempting to replicate the search functionality of icomoon where typing a word displays related images. However, I'm facing an issue where I can't seem to get the value entered in the input field to trigger an ...

Arranging Data by Date in Mongoose with MongoDB and Mlab

The data is currently stored in mlab as shown below: { "_id": { "$oid": "576c89c00662d4e4a548728f" }, "createddate": { "$date": "2016-06-24T01:15:44.362Z" }, "_idapt": "5754cec6dcba0f2aab5c0bca", "originalname": "Ja ...

Updating the appearance of tabs in React Native Navigation dynamically during runtime

I am currently working with the startTabBasedApp API, which includes three tabs in my app. I have a requirement to change the background color of the tabBar for specific screens dynamically. Is it possible to achieve this at runtime? For instance: Scree ...