Express-Validator模块使用新函数: req.getValidationResult()如果验证中有任何错误,此函数将返回一个对象。该对象看起来像:
{param: "field name", msg: "error message", value: "<field input value>"}
问题是 - 如何从对象返回.msg参数?当我使用
req.getValidationResult().then(function(result){
if(!result.isEmpty()) {
console.log(result.array());
//return;
} else {
console.log('Validation Ok');
}
该函数返回一个数组。但我只需要.msg。
答案 0 :(得分:3)
代码应为以下
req.getValidationResult().then(function (result) {
if (!result.isEmpty()) {
var errors = result.array().map(function (elem) {
return elem.msg;
});
console.log('There are following validation errors: ' + errors.join('&&'));
res.render('register', { errors: errors });
} else {
答案 1 :(得分:0)
req.getValidationResult().then(function(result){
const {msg} = result;
if(msg != undefined) {
console.log(msg);
//return;
} else {
console.log('Validation Ok');
}
答案 2 :(得分:0)
request.getValidationResult().then(function(result) {
if (result.array() != '') {
response.render('route',{validation:result.array()})
return;
return;
} else {
//valid
}
});
视图:
<% if(validation) {%>
<ul>
<% for(var i = 0;i< validation.length;i++){ %>
<li><%= validation[i].msg %></li>
<%}%>
</ul>
<% }%>
答案 3 :(得分:0)
req.getValidationResult().then((result) => {
if(result.isEmpty){
if(result.array().length > 1){
return console.log(result.array())
}else{
const noticias = {
titulo: req.body.titulo,
noticia: req.body.noticia,
resumo: req.body.resumo,
autor: req.body.autor,
data_noticia: req.body.data_noticia
}
new noticiasdb(noticias).save().then(() => {
res.redirect('/noticias')
}).catch((err) => {
console.log(`ERRO AO SALVAR ERRO: ${err}`)
})
}
}
})