express-validator isEmpty 没有错误
No errors with express-validator isEmpty
我在 expressjs 应用程序中使用 express-validator 5.2.0。我在表单数据上实现了验证。但它不捕获错误并给出空的错误对象。当验证运行时,它会在我提交空表单时显示 "no error"。它应该遵循错误路径并显示错误。
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');
}
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()
.notEmpty() 添加一个验证器来检查一个值是否不为空;即,长度为 1 或更大的字符串。
https://express-validator.github.io/docs/validation-chain-api.html#notempty
我在 expressjs 应用程序中使用 express-validator 5.2.0。我在表单数据上实现了验证。但它不捕获错误并给出空的错误对象。当验证运行时,它会在我提交空表单时显示 "no error"。它应该遵循错误路径并显示错误。
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');
}
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()
.notEmpty() 添加一个验证器来检查一个值是否不为空;即,长度为 1 或更大的字符串。
https://express-validator.github.io/docs/validation-chain-api.html#notempty