Node.js(Express)表单在提交时清除 [英] Node.js (Express) Form Clears on Submission

查看:144
本文介绍了Node.js(Express)表单在提交时清除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Node.js(使用Express)中的一个非常基本的注册表单,并且我试图找到最简单的方式来提供基本的表单验证。我已经去了快速验证器,这似乎做得很好。但是,我的目标是简单地显示所需的任何验证消息,并且保留用户单独输入的值。

I am working on a really basic registration form in Node.js (with Express), and I am trying to find the easiest way to provide basic form validation. I've gone with "Express-Validator", which seems to do a fine job. However, my goal is to simply show any validation messages that are required and to leave the values entered by the user alone.

请求信息没有回到res.render,我猜是有道理的。但是,我看到无处不在,我找不到任何参考,讨论如何在显示错误消息后填写表单字段。

It seems that the request information is not making it back into the res.render, which I guess makes sense. However, I've looked everywhere I can think of and I can't find any reference that discusses how to keep form fields populated after showing error messages.

下面是一个描述我的方法的小代码片段:

Below is a small snippet describing my approach:

post: function(req, res){

            var userName = req.body.username;
            var password = req.body.password;

            //Validate input
            req.assert("username", 'Invalid email address.').isEmail();
            req.assert("password", 'Password cannot be empty.').notEmpty();
            req.assert("passwordConfirm", 'Passwords entered do not match!').equals(password);

            //Make sure we have no validation errors
            var pageErrors = req.validationErrors();
            if(!pageErrors)
            {
                userModel.CreateUser(userName, password, function(err){
                    if(err)
                    {
                        //there was a problem inserting new user... probably already exists
                        //will need to check the error to confirm
                        var dbErrorMessage = "Could not insert record into database!";
                        if(err.code === 11000)
                        {
                            //this is a duplicate entry
                            dbErrorMessage = "A user with that email address already exists!";
                        }

                        res.render('register.html', { pageErrors: [{msg: dbErrorMessage }]});
                    }
                    else
                    {
                        res.render('register.html', { successMessage: successMessage });
                    }
                });
            }
            else
            {
                res.render('register.html', { pageErrors: pageErrors });
            }


推荐答案

不幸的是,你必须重新填充表单手动。如果您遇到任何页面错误,您将会将表单值传回给视图。

Unfortunately, you have to repopulate the form manually. If you get any page errors, you will pass back the form values to the view.

        if(!pageErrors)
        {
            // ...
        }
        else
        {
            res.render('register.html', { 
                pageErrors: pageErrors,
                userName: userName
            });
        }

在你看来,你会做一个简单的检查,看看他们是否任何错误并相应地重新填补。您必须跟踪每个表单域出现的错误。

And in your view, you would do a simple check to see if their are any errors and repopulate accordingly. You would have to keep track of what errors are produced for each form field.

<% if (userNameError) { %>
    <input type="text" name="userName" value="<%- userName %>" />
<% } else { %>
    <input type="text" name="userName" />
<% } %>

另一种流行的方式是将您的表单通过ajax发送到服务器,并进行所有验证。如果有错误,输入的表单数据将保留,并显示错误,否则成功登录后重定向。以下是如何使用javascript提交表单的示例。

Another popular way is to send your form via ajax to to the server, and do all your validations. If there is an error, the entered form data remains and you would show the error, otherwise redirect after the successful login. Below is an example of how to submit a form with javascript.

$("#login-button").live("submit", function (e) {

    // this will prevent the form from being uploaded to the server the conventioanl way
    e.preventDefault();

    // the form data
    var data = $(this).serialize();

    // this logs the user in 
    $.ajax({
        type: 'POST',
        url: BASE_URL + '/login',
        data: data,
        dataType: 'json',
        success: function (data, status) {
            // successful
        },

    });

    // superfluous fallback
    return false; 
}); 

这篇关于Node.js(Express)表单在提交时清除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆