Eliminating empty spaces within the Express Validator

I struggle with regex, but I am currently using it on the frontend along with Joi in order to eliminate blank spaces from phone numbers for validation purposes. Surprisingly, it actually works:

input: 0758541287 8

Valid:

Joi.string().trim().replace(/\s*/g,"").pattern(new RegExp(/^0([1-6][0-9]{8,10}|7[0-9]{9})$/))

On my server, utilizing express-validator, I expected it to remove the spaces as well, but unfortunately, it does not work as intended:

Not Valid:

body('phone')
    .isString()
    .replace(/\s*/g,"")
    .matches(/^0([1-6][0-9]{8,10}|7[0-9]{9})$/)
    .withMessage('Please enter a UK phone number'),

Also not working:

body('phone')
    .isString()
    .custom(value => Promise.resolve(value.replace(/\s*/g, "")))
    .matches(/^0([1-6][0-9]{8,10}|7[0-9]{9})$/)
    .withMessage('Please enter a UK phone number'),

Validation Error:

  validationErrors: [
    {
      value: '0748431287 8',
      msg: 'Please enter a UK phone number',
      param: 'phone',
      location: 'body'
    }
  ],

I could manually remove the spaces before sending the request, but I am genuinely curious as to why this behavior is occurring?

Answer â„–1

When using a custom validation method, it may return undefined (since that's the result of console.log(...)), leading to the field being considered invalid.

It's worth noting that the documentation for replace doesn't mention regular expressions. It could be possible that it only replaces substrings instead?

Additionally, there is no reference to matches in the documentation either.

To address these issues, you can utilize standard Javascript functions like replace and match within a custom validation method:

body("phone")
  .isString()
  .custom(value => value.replace(/\s*/g, "")
                        .match(/^0([1-6][0-9]{8,10}|7[0-9]{9})$/))
  .withMessage("Please enter a UK phone number")

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

Ways to resolve the issue of TypeScript download file not displaying the download window

In my React application, I implemented this TypeScript code to facilitate file downloads: const handleDownloadPdf = async (pdfUrl: string) => { if (!pdfUrl) { toast.error("PDF url is null"); return; } try { ...

Navigating Parse object attributes within AngularJS

Currently, I am in the process of developing an AngularJS application that utilizes data from a parse-server backend. To retrieve this data, I use services that are called from my controllers. However, as Parse objects require all properties to be accessed ...

What are the benefits of installing both libraries A (react-router) and B (react-router-dom) together, especially when library B relies on library A for functionality

I am currently exploring the necessity of explicitly specifying all dependencies in the packages.json file. For instance, when I want to utilize the react-router library. According to the official documentation: npm install react-router@6 react-router-d ...

Nuxt js is throwing an error stating that it is unable to locate the pages directory

I have made changes to the folder structure of my Nuxt.js project. I am encountering an issue: Error - Couldn't find a pages directory in D:\sample. How can I access the pages? .nuxt, app, node_modules, server, .eslintrc, package, package-lock ...

What is the best way to transmit progress streams with Node and Express?

Currently, I am working on a Video Resizer website where I need to keep the user updated on the progress of video conversion. Most tutorials about this use SSE with get requests and EventSource for listening. In my case, it involves a post request that in ...

Tips for eliminating the trailing slash from the end of a website article's URL

I've recently delved into learning Gatsby, and I've encountered an issue with the Open Graph tag in my project. The og:image is displaying a different image than the intended thumbnail for the article. Here's an example article - . When try ...

The rule 'import/no-cycle' definition could not be located

After removing my npm package along with the package.lock.json file, I proceeded to run 'npm install' and followed up with 'npm update'. However, upon starting my application using 'npm run start', an error occurred. Upon lau ...

What could be causing the issue with converting a Firestore timestamp to a Date object in my Angular app?

Currently, I am developing an Angular project that involves using a FireStore database. However, I have encountered a problem with the setup. Within my Firestore database, I have documents structured like the example shown in this image: https://i.sstatic ...

What is the best way to compel Angular to recompile a template using jQuery?

Even though the solution may not be perfect, I am dealing with legacy code and various limitations. In my application, there is a page where users can choose from several forms to fill out. Once a form is selected, we utilize JQuery to load it into the DO ...

Is it just me or does escape() not work reliably?

With the use of JavaScript, I am able to generate HTML code dynamically. For instance, I can add a function that triggers when a link is clicked, like so: $('#myDiv').append('<a href="javascript:start(\''+TERM+'\ ...

Converting Node JS request to an API into React Fetch syntax

I have encountered a problem while developing an app in React-Native that connects with the Hubspot API. Initially, I tried to make the request using the Node JS request module, but it didn't work well with React Native when Expo was involved. Now, I ...

Ensure that the form validation process includes a Captcha code for added

Can you demonstrate how to incorporate the following code into a validation check within a form: $("form").clientSideCaptcha({ input: "#captchaText", display: "#captcha", pass : function() { alert("Verification succe ...

Add a Filter to the Observer (__ob__) in Typescript

I am trying to implement a filter using this.Grid.option("dataSource").filter(x => x.Placeholder != null) however, it doesn't seem to be working when I run console.log(this.Grid.option("dataSource")); I receive (72) [{…}, {…}, {…}, {†...

Error: Unable to execute map() function on commands.options? while configuring slash commands

discord js v13.3.1 I have configured my bot to update and deploy slash commands using a specific command called "deploy". The structure of the deploy command is as follows: module.exports = { name: "deploy", description: "deploys sl ...

How can I transfer information from one page to another in Next.js 14 without displaying the data in the URL?

As a React Native developer working on a web app, I'm facing a challenge with passing data from one page to another in Next.js 14 without displaying the data in the URL. I have a specific app directory within my Next.js project. When I mention not sh ...

Having trouble with VueJS ref not preventing the default form action on submit?

Within my <script> tag, I currently have the following code: render(createElement) { return createElement("form", {ref: "formEl" , on: {submit: this.handleSubmit} }, [ <insert create form inputs here> ]); } handleSubmit(e) { ...

Transform a button to function like a checkbox in Knockout JS

Essentially, I have implemented a feature on my website where a button changes its color from green to grey and vice versa when clicked, giving the illusion of turning on and off. Below is the JavaScript and HTML code for this button: <script> $(&ap ...

Configuring the session expiration time in Node.js Express by setting it in the SessionStore rather than in a cookie

Every resource I have come across regarding Express Sessions focuses on setting the cookie expiration times. session.cookie.expires = null; // Browser session cookie session.cookie.expires = 7 * 24 * 3600 * 1000; // Week long cookie However, the cookie ...

Speedy start-up with callback for asynchronous initialization

Currently, I am utilizing express to dynamically add routes based on data stored in a MongoDB configuration. const app = require('express')(); const mongoose = require('mongoose'); var proxyHandler = { paths: [ '/demoservic ...

I am not encountering any errors; however, upon entering the room, my bot fails to initiate creation of a new channel

const Discord = require("discord.js") const TOKEN = "I forgot to include my token here" const { Client, GatewayIntentBits } = require('discord.js'); const { MemberFetchNonceLength } = require("discord.js/src/errors/Erro ...