Aru*_*mar 1 express express-validator
我在expressjs应用程序中使用express-validator 5.2.0。我在表单数据上实现了验证。但是它不会捕获错误,而是提供空错误对象。验证运行时,当我提交空白表格时,它显示“无错误”。它应遵循错误路径并应显示错误。
var express = require('express');
var router = express.Router();
const { check, validationResult } = require('express-validator/check');
router.post('/register', [
check('firstName', 'First Name is required').isEmpty(),
check('lastName', 'Last Name is required').isEmpty(),
check('username', 'User Name is required').isEmpty(),
check('password', 'Password is required').isEmpty()
], (req, res, next)=>{
let errors = validationResult(req);
if (!errors.isEmpty()) {
console.log(errors.mapped());
console.log("errors")
return res.render('auth/register', { errors: errors.mapped() })
}else{
console.log('no errors')
return res.render('auth/login');
}Run Code Online (Sandbox Code Playgroud)
gus*_*nke 11
check('firstName', 'First Name is required').isEmpty() 强制firstName为空。
您将需要将最后一部分更改为.not().isEmpty(),以便反转isEmpty验证器。
可能也会对您感兴趣:https : //github.com/express-validator/express-validator/issues/476
在您的代码片段中,您尚未添加验证器来检查值是否不为空。您可以通过执行以下操作来实现此目的:
check('firstName', 'First Name is required').notEmpty()
Run Code Online (Sandbox Code Playgroud)
.notEmpty()添加一个验证器来检查值是否不为空;即长度为1或更大的字符串。
https://express-validator.github.io/docs/validation-chain-api.html#notempty
| 归档时间: |
|
| 查看次数: |
3656 次 |
| 最近记录: |