简体   繁体   English

删除 Express Validator 中的空格

[英]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.我对正则表达式不是很好,但我在前端使用以下内容与 Joi 一起从电话号码中删除空格以进行验证。 It seems to work:它似乎工作:

input: 0758541287 8输入: 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:我的服务器使用express-validator ,我很惊讶这并没有删除空格:

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?我可以在提出请求之前删除空格,但我很想知道为什么这不像我想象的那样表现?

Your custom validation method returns undefined (because that's what console.log(...) returns), which is interpreted to mean that the field is invalid.您的自定义验证方法返回undefined (因为这是console.log(...)返回的内容),这被解释为该字段无效。

Moreover, the documentation for replace does not mention regular expressions.此外, replace的文档没有提到正则表达式。 Perhaps it replaces only substrings?也许它只替换子字符串?

Finally, matches does not appear in the documentation either.最后, matches也不会出现在文档中。

You can use the normal Javascript functions replace and match inside a custom validation method:您可以在自定义验证方法中使用普通的 Javascript 函数replacematch

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM