1

I am trying to add a validation method to my ExpressJS app, however it does not quite seem to work out... I can currently change the username, however if it has an empty String, the app crashes, although it is supposing to send an error. Any suggestions?

var validatePresenceOf = function(val, func) {
    if (typeof val === 'undefined' || val.length < 1) {
        res.json({
            errors: {
                userName: "Your name can't be blank"
            }
        });
    } else {
        return func;
    }
};

validatePresenceOf(req.body.userName, User.findByIdAndUpdate( currentUser._id, {
    local: {
        name                : req.body.userName
    }
}, function (err, user) {

    if (err) throw err;

    res.json({
        user : user
    });
}));
user3048402
  • 1,349
  • 1
  • 12
  • 29
  • Your error should have a stack trace that has a reference to your code. Track down that line number and edit it into your question. Also, [this question](http://stackoverflow.com/questions/7042340/node-js-error-cant-set-headers-after-they-are-sent) covers the headers problem very thoroughly if you haven't seen it. – Patrick M Jul 19 '14 at 02:49

2 Answers2

0

Express gives error when setHeader method called twice. Maybe you forgot or didn't use the "return" when validation method gives the error! Please check this. I'm believing express validator is better solution for you

enxtur
  • 2,395
  • 1
  • 16
  • 16
0

You should not call User.findByIdAndUpdate() immediately before validation check.

This one can temporarily fix your issue:

var validatePresenceOf = function(val, func) {
    if (typeof val === 'undefined' || val.length < 1) {
        res.json({
            errors: {
                userName: "Your name can't be blank"
            }
        });
    } else {
        func();
    }
};

validatePresenceOf(req.body.userName, function() {
    User.findByIdAndUpdate( currentUser._id, {
        local: {
            name: req.body.userName
        }
    }, function (err, user) {

        if (err) throw err;

        res.json({
            user : user
        });
    });
});

However, I would recommend using express-validator as a best practice for request validation.

haotang
  • 5,520
  • 35
  • 46