【问题标题】:I need to loop through html in elements in ejs file to check for errors我需要遍历 ejs 文件中元素中的 html 以检查错误
【发布时间】:2018-03-15 17:48:41
【问题描述】:

这是我的 ejs 文件。我基本上是在使用 express JS 创建一个身份验证应用程序。我需要遍历名称、用户名、电子邮件和密码,如果它是空的,我想打印出一条错误消息。这是ejs文件:

<div class="container-fluid">

    <div class="header">
        <h1>Account Registration</h1>
    </div>

    <% if(error) { %>

    <% for(var i = 0; i (dunno what to do here) %>

    <% } %>

    <form action="/users/register" method="POST">
        <div class="database">

            <label>Name</label>
            <input type="text" name="name" class="form-control" placeholder="Name">

            <label id="email">Email</label>
            <input type="text" name="email" class="form-control" placeholder="Email">

            <label id="username">Username</label>
            <input type="text" name="username" class="form-control" placeholder="Username">

            <label id="password">Password</label>
            <input type="text" name="password" class="form-control" placeholder="Password">

            <label id="password2">Confrm Password</label>
            <input type="text" name="password2" class="form-control" placeholder="Conform Password"><br>

            <button type="submit" class="btn btn-primary mb-4">Submit</button>

        </div>
    </form>

</div>

这是 register.ejs 的 router.post 文件

router.get('/login', function(req, res){
  res.render('login');
});

//post register
router.post('register', function(req, res) {
    var name= req.body.name;
    var username= req.body.username;
    var email= req.body.email;
    var password= req.body.password;
    var password2= req.body.password2;

//Validating
    checkBody('name', "Name is required").notEmpty();
    checkBody('username', "Username is required").notEmpty();
    checkBody('email', "Email is required").notEmpty();
    checkBody('email', "Email is in wrong format").isEmail();
    checkBody('password', "Password is required").notEmpty();
    checkBody('password2', "Passwords did not match").isEqual(req.body.password);

    var errors = req.validationErrors();

    if(errors){
        res.render('register', {errors:errors})
    }else{
        var newUser = User({
            name: name,
            email: email,
            username: username,
            password: password
        });

    }
});

我是 express js 的新手。将不胜感激。谢谢。希望你能理解我的问题,

【问题讨论】:

  • checkBody(...) 里面有什么代码?上面的代码你面临什么问题?

标签: node.js express


【解决方案1】:

您可以遍历所有错误并使用ulli 标签显示它们

<% if (errors.length > 0) { %>
        <ul>
            <% for (var i = 0; i < errors.length; i++) { %>
               <li><%= errors[i].msg %></li>
            <% } %>
        </ul>
<% } %>

【讨论】:

  • {{#if errors}} {{#each errors}} &lt;div class="alert alert-danger"&gt;{{msg}}&lt;/div&gt; {{/each}} {{/if}} 我只需要这些hbs代码转换成ejs
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-23
  • 1970-01-01
  • 2020-08-28
  • 1970-01-01
  • 2019-02-02
  • 1970-01-01
相关资源
最近更新 更多