Home > Software design >  Removing blank spaces in Express Validator
Removing blank spaces in Express Validator

Time:06-07

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?

CodePudding user response:

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")
  • Related