Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Stopping execution flow after an error in express-validator

Stopping execution flow after an error in express-validator

Problem

I'm using express-validator to do form validation on the request object in Express. I do something like the following:

req.onValidationError(function(msg) {
    res.render('signup', { error: msg });
});

req.check('email', 'Please enter a valid email.').len(1,256).isEmail;
req.check('password', 'Your password must be at least 8 characters.').len(8,256);

var user = {
    email: req.body.email,
    password: req.body.password
};

User.create(user, function(err, result) {
    console.log(err, result);
});

res.render('signup');

The problem is that execution flow continuse, and it tries to render the same resource twice, while executing my User.create() method. It'll also throw an Error: Can't use mutable header APIs after sent. because of the attempted double-rendering.

How can I prevent this from happening?

Problem courtesy of: Josh Smith

Solution

see https://github.com/ctavan/express-validator#readme

var errors = [];
req.onValidationError(function(msg) {
    //res.render('signup', { error: msg });
    errors.push(msg);
});

req.check('email', 'Please enter a valid email.').len(1,256).isEmail;
req.check('password', 'Your password must be at least 8 characters.').len(8,256);

if (errors.length) return res.render('signup', { error: errors.join('\n') });

var user = {
    email: req.body.email,
    password: req.body.password
};

User.create(user, function(err, result) {
    console.log(err, result);
});

res.render('signup');
Solution courtesy of: thejh

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Stopping execution flow after an error in express-validator

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×