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?