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

"Typescript: Unraveling the Depths of Nested

Having trouble looping through nested arrays in a function that returns a statement. selectInputFilter(enteredText, filter) { if (this.searchType === 3) { return (enteredText['actors'][0]['surname'].toLocaleLowerCase().ind ...

Challenge with Expect.js validation in a lesson on Codeacademy

I am currently developing a lesson on Codecademy to teach users about the construction of HTML forms. This project is mainly for my own enjoyment, just to keep everyone in the loop. After reviewing the submission test guidelines and API, I made the decisio ...

Tips on blending a background with three.js sprite image?

Currently, I am facing issues with blending sprites in three.js to load textures for points (originally a pointcloud). Unfortunately, the blending does not seem to work correctly. Below is the code snippet that I am using: this._renderer = new THREE.WebGL ...

Error message: The function for the AJAX call is not defined

I'm currently working with jQuery's ajax function and encountering an error: 'getQty is not defined' Can you spot my mistake here? jQuery Code: function getQty() { var dataString = "itemId=" +$(".itemId").val(); $.ajax({ t ...

What causes the slash URL to behave differently than other URLs when running through the middleware of NodeJS?

When I type http://localhost:3000/product into the browser, why do I see output for both '/' and '/product'? Take a look at this code snippet below. const express = require('express'); const app = express(); // http://loca ...

I need help troubleshooting my Axios frontend POST request in React to the backend Express POST. The console is displaying the request as a POST with a status of

Browser: Safari Texteditor: VS CODE Frontend framework: Reactjs Backend setup: Express.js Issue: I am encountering a problem with an Axios post request on the front end after triggering an onClick call event. I am unable to debug the data being sent in ...

The valueChanges event of a Reactive Form is activated whenever options from a datalist are selected

Whenever a user types into the input field, I am making an API call to retrieve and display data in a datalist for autocompletion (typeahead). control.get('city').valueChanges.pipe( map((searchText) => searchText.trim().toLowerCase()), fi ...

difficulty in making an https request

My application was developed using OFFICEjs and was functioning properly on LOCALHOST. However, last week it suddenly started throwing an error message - "XHR Error." This issue arose out of nowhere, as I hadn't made any changes to the code over the w ...

Ways to eliminate the worldwide model in SAPUI5

I've been attempting to break down the global model without success. I have a filter button that's set up like this: navToSecond : function (oEvent){ var oObject = this.getView().byId("inp").getValue(); sap.ui.getCore().setModel( ...

`ACCESS DENIED: Unauthorized access attempt detected in Node.js``

When attempting to connect, MySQL is establishing a connection with an unfamiliar IP address. Refer to the code below: .env MYSQL_HOST=domain.example.com MYSQL_USER=**** MYSQL_PASSWORD=**** MYSQL_DB=**** MYSQL_PORT=3306 connection.js const mysql = requir ...

Ways to insert a line break within a jQuery function using text()

I am looking to add a new line in my jQuery function. $.ajax({ url:"http: //192.168.1.4/Experiements/webservices/api.php", type:"GET", dataType:"json", data:{type:"login", UserName:userId,Password:userPassword}, ...

Is there a way to update the Angular component tag after it has been rendered?

Imagine we have a component in Angular with the selector "grid". @Component({ selector: 'grid', template: '<div>This is a grid.</div>', styleUrls: ['./grid.component.scss'] }) Now, when we include this gri ...

most efficient method to execute numerous API requests at the same time

Currently, I am developing a backend using expressJS. Imagine that I need to make 10,000 calls to an API consecutively and store the obtained data in a database. What would be the most effective approach for achieving this task? Is it possible that Promis ...

I'm looking to find the Angular version of "event.target.value" - can you help me out?

https://stackblitz.com/edit/angular-ivy-s2ujmr?file=src/app/pages/home/home.component.html I am currently working on getting the dropdown menu to function properly for filtering the flags displayed below it. My initial thought was to replicate the search ...

Guidelines for implementing drag and drop functionality for my specific scenario

Looking to create a restricted area for dragging elements within my app. Specifically, I want the element to only be draggable within a certain defined space. Here is what I currently have: http://jsfiddle.net/L73T5/10/ html <div id='background ...

After attempting to authenticate using my Gmail account, I receive the message "ERROR GET /auth/google/callback TokenError: Unauthorized"

Whenever I attempt to log in using Google authentication, I encounter an issue. After selecting an account, I receive the following error message: "ERROR GET /auth/google/callback TokenError: Unauthorized". How can I resolve this problem with authenticatin ...

Change the label's class when the input area is selected

Looking to add a new class to a label when its corresponding input element is in focus. A form consists of 10 input fields and 10 labels, one for each field. const inputFields = document.querySelectorAll('.form-control'); console.log(inputFie ...

Embracing Micro Front End Development

Currently, I have a legacy AngularJS (Angular 1) app that cannot undergo any major changes at the moment. A new standalone app has been created using a newer stack. The goal is to integrate this new app into the old legacy app without making significant m ...

The PHP script encountered an issue with the HTTP response code while processing the AJAX contact form, specifically

Struggling to make this contact form function properly, I've tried to follow the example provided at . Unfortunately, all my efforts lead to a fatal error: "Call to undefined function http_response_code() in /hermes/bosoraweb183/b1669/ipg.tenkakletcom ...

Discover the nearest class and smoothly expand it with the slideDown function in jQuery

Hey there, I'm working on implementing a "View More" button on my page. The button will reveal another unordered list that currently has the class of "hidden-list". When the user clicks on "View More", I want it to slideToggle the hidden-list element ...