Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

440
Vistas
Removing blank spaces in Express Validator

I'm not very good with regex, but I'm using the following on the frontend with Joi to remove blank spaces from a phone number for validation. It seems to work:

input: 0758541287 8

Valid:

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

My server uses express-validator, and I'm just surprised that this isn't removing the spaces:

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 just remove the spaces before I make the request, but I'm interested in knowing why this isnt' behaving as I would imagine?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Your custom validation method returns undefined (because that's what console.log(...) returns), which is interpreted to mean that the field is invalid.

Moreover, the documentation for replace does not mention regular expressions. Perhaps it replaces only substrings?

Finally, matches does not appear in the documentation either.

You can use the normal Javascript functions replace and match inside 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")
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda