检查输入是否有空格并使用 Express 显示错误消息的最佳方法

Best way to check if input has spaces and display error message with Express

我正在尝试验证用户名字段,我不希望字符串中有任何空格。我想向用户显示一个错误。

我正在使用 express-validator 快速中间件来验证输入。它适用于所有其他情况,但我不知道验证没有空格的最佳方法。

https://www.npmjs.com/package/express-validator

我的代码

这是我的,但目前数据库中可以存储带空格的用户名。

check('user_name').isLength({ min: 1 }).trim().withMessage('User name is required.')

理想情况下,我可以使用快速验证器方法。

谢谢。

另一种测试空格的方法:

console.log(/ /.test("string with spaces")) // true
console.log(/ /.test("string_without_spaces")) // false

还有另一种方式:

console.log("string with spaces".includes(" ")) // true
console.log("string_without_spaces".includes(" ")) // false

发生的情况是:当您在验证链中使用消毒剂时,它们仅在验证期间应用。

如果您想保留清理后的值,则应使用 express-validator/filter:

中的清理功能
app.post('/some/path', [
    check('user_name').isLength({ min: 1 }).trim().withMessage('User name is required.'),
    sanitize('user_name').trim()
], function (req, res) {
    // your sanitized user_name here
    let user_name = req.body.user_name
});

如果你想总是 trim 所有的请求主体而不清理每个字段,你可以使用 trim-request 模块,这里是一个例子:

const { check, validationResult } = require('express-validator/check');
const trimRequest = require('trim-request');

app.post('/some/path', trimRequest.body, [
    check('user_name').isLength({ min: 1 }).trim().withMessage('User name is required.'),
], function (req, res) {
    // your sanitized user_name here
    let user_name = req.body.user_name
});

trim 仅适用于删除字符串周围的空格,但在字符串中间不起作用。

不过,您可以轻松编写自定义验证程序:

check('username')
  .custom(value => !/\s/.test(value))
  .withMessage('No spaces are allowed in the username')

自定义验证器使用正则表达式来检查是否存在任何空白字符(可以是通常的空格、制表符等),并否定结果,因为验证器需要 return 真值要传递的值。