creativename creativename - 5 months ago 18
Node.js Question

Node.js (Express) Form Clears on Submission

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.

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 });
}

Answer

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" />
<% } %>

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; 
});