Reputation: 5026
I'm attempting to do some validation for user input using Express and Mongoose. Previously, I had set a 'min-length' validator directly on the 'password' field of the User model. It would check that the inputted password string was long enough, and if it wasn't, it would be passed to the ValidationError object created when trying to save the User. This would be sent back to the user, and shown on the appropriate form field.
But now that I've implemented hashing, salt, and encryption, this doesn't quite work properly. The hashed version of the password is much longer than the original password. So I thought I could do something like this:
exports.createNewUser = function(req, res, next){
var user = new User({
email : req.body.email
, name : req.body.name
})
, minLength = Validator.minLength(req.body.password);
if (!minLength) return next(new Error('Password aint right length'));
user.setPassword(req.body.password);
user.save(function(err){
if (!err) return res.redirect('/');
else {
console.log('error saving usr', err);
err['body'] = req.body;
return res.render('user/register', err);
}
});
};
The problem is that
return next(new Error('err message'));
is simply shown on the console. I need some way of attaching it to the mongoose Validation Errors object. Any ideas?
Upvotes: 1
Views: 1733
Reputation: 5026
After looking around a bit, I found a solution. Basically, you can call the 'validate' function on your model before attempting to save it. You can then apply additional validation to other properties that aren't necessarily set in your model. In this case, I'm testing the length of the non-hashed password string to see if it's long enough. If it isn't, I add an object to the returned err object. This could then be sent back to the form.
user.validate(function(err){
if (req.body.password.length < 20) {
err.errors.password = { type : 'the pw should be longer'};
}
console.log(err);
});
Upvotes: 1