Express Validator - 只允许使用字母、数字和一些特殊字符

问题描述

在前端使用 JavaScript,我创建了允许字母、数字和一些特殊字符的正则表达式......

    function onlyAlphaSomeChar(value) {
      const re = /^[A-Za-z0-9 .,'!&]+$/;
      return re.test(value);
   }

如果我在后端使用 express-validator 构建验证过程,那么这会是什么?

我在 Expressjs 环境中创建了这么多,但不确定接下来的步骤应该是什么样子...


//...

app.post('/',[
    //VALIDATE
    check('comment')
        .notEmpty()
        .withMessage('Comment required')
        .isLength({min: 3,max:280})       
        .withMessage('Comment must be between 3 and 280 characters')
        .escape()
],(req,res) => {

//...

});


解决方法

要检查正则表达式,您可以使用 .match(regexp)

因此,在这里,您可以:

//...

app.post('/',[
    //VALIDATE
    check('comment')
        .escape()
        .notEmpty()
        .withMessage('Comment required')
        .isLength({min: 3,max:280})       
        .withMessage('Comment must be between 3 and 280 characters')
        .matches(/^[A-Za-z0-9 .,'!&]+$/)
],(req,res) => {

//...

});
```

Does this answer your question?