每个字段只显示1条错误消息Express-validator

时间:2017-06-27 10:13:17

标签: node.js express

我已经使用ExpressJs和pug(模板)创建了一个基本的身份验证应用程序并且正在运行,但是当身份验证失败时,它会显示同一字段的多个错误消息。

Login.pug

body
    div.columns

      div.card.column.is-4.is-offset-4
       if(error)
        p.help.is-danger #{error}
       form(action="/account/login",method="post")
         div.card-content
            div.content
               div.field
                 p.control
                   input(type="text", placeholder="Email", name="email").input.is-primary.is-outlined
                   if(errors)
                     for error in errors
                         if (error.param=='email')
                            p.help.is-danger #{error.msg} 

               div.field
                 p.control
                   input(type="password", placeholder="Password", name="password").input.is-primary.is-outlined
                   if(errors)
                      for error in errors
                         if (error.param=='password')
                            p.help.is-danger #{error.msg}



         button(type="submit",align="right").button.is-primary.is-outlined.is-pulled-right Login

路线(account.js)

req.checkBody('email', 'Email is required').notEmpty();
req.checkBody('email', 'Email must be valid').isEmail();
req.checkBody('password', 'Password is required').notEmpty();
req.checkBody('password', 'Password must be 8-16 characters long').isLength(8);
var errors = req.validationErrors();
if (errors) {
    res.render('login', { errors: errors });
}

enter image description here

我想要的是显示单个字段的单个错误消息

1 个答案:

答案 0 :(得分:0)

找到我自己的问题的答案

在循环中添加-break导致只打印一条消息,如 -

if(errors)
   for error in errors
     if (error.param=='email')
        p.help.is-danger #{error.msg} 
        -break
相关问题