Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

439
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda