Express Validator - 只允许字母、数字和一些特殊字符
Express Validator - Only allow letters, numbers and some special characters
在前端使用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?
在前端使用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?