此代码工作正常。它会抛出错误并显示在网页上。但现在我想选择个别错误并显示在网页上。
// request.body validation
req.checkBody('email', 'Email is required.').notEmpty();
req.checkBody('name', 'Name is required.').notEmpty();
req.checkBody('phone', 'Phone is required.').isMobilePhone('en-IN');
req.checkBody('password1', 'Password is required.').isLength({min:6});
req.checkBody('password2', 'Password not same, try again!!').equals(password1);
var errors = req.validationErrors();
if (errors) {
console.log(req.body.params.errors);
res.render('form', {
errors: errors,
isForm: true,
register: true
});
} else {
console.log('PASSED');
}
console.log的错误代码是什么代码?
答案 0 :(得分:0)
最简单的方法是启用mapped
。这使得errors
数组成为普通对象,因此您可以使用点语法访问特定错误:
var errors = req.validationErrors(true); // note the true argument
if (errors) {
console.log(errors);
res.render('form', {
errors: errors.phone, // ordinary object access syntax
isForm: true,
register: true
});
} else {
console.log('PASSED');
}
您也可以将映射设置为false。这是默认方式。
errors
变量就是一个数组,所以你可以像访问任何其他数组一样访问它的元素:
if (errors) {
res.render('form', {
errors: errors[0], // only the first error
isForm: true,
register: true
});
} else {
console.log('PASSED');
}
如果要发送属于特定字段的元素,可以使用for循环在errors
中查找其位置:
// request.body validation
req.checkBody('email', 'Email is required.').notEmpty();
req.checkBody('name', 'Name is required.').notEmpty();
req.checkBody('phone', 'Phone is required.').isMobilePhone('en-IN');
req.checkBody('password1', 'Password is required.').isLength({ min: 6 });
req.checkBody('password2', 'Password not same, try again!!').equals('password1');
var errors = req.validationErrors();
if (errors) {
// look for phone
let indexOfPhone = -1;
for (let i = 0; i < errors.length; i += 1) {
if (errors[i].param === 'phone') indexOfPhone = i;
}
res.render('form', {
errors: errors[indexOfPhone],
isForm: true,
register: true
});
} else {
console.log('PASSED');
}
答案 1 :(得分:0)
使用 req.validationErrors()在 errors变量中包含一个或多个值的情况下,使用简单的for循环打印参数。
req.checkBody('email', 'Email is required.').notEmpty();
req.checkBody('name', 'Name is required.').notEmpty();
req.checkBody('phone', 'Phone is required.').isMobilePhone('enIN');
req.checkBody('password1', 'Password is required.').isLength({min:6});
req.checkBody('password2', 'Password not same, try again!!').equals(password1);
var errors = req.validationErrors();
if (errors) {
// true condition : errors has values stored in it
// printing out the params of each error using a for loop
var i;
for (i = 0; i < errors.length;i++)
{
console.log(i," : ",errors[i]['param']); // printing out the params
}
res.render('form', {
errors: errors,
isForm: true,
register: true
});
} else {
// false condition : errors is empty
console.log('PASSED');
}