I attached the Registration form and Validation code (Node.js) as shown below. I have tried out to validate user input which comes from the registration form, but it hasn't worked out! But it was successfully stored on the MongoDB database.
<form action="/register" method="POST">
<input type="text" name="name" placeholder="username"><br>
<input type="password" name="userpass" placeholder="password"><br>
<input type="submit" name="submit" value="send">
</form>
router.post('/register', function(req, res, next) {
// Get user input from register form
let nam = req.body.name;
let pass = req.body.userpass;
req.checkBody('nam', 'Name is required').notEmpty();
req.checkBody('pass', 'Pass is required').notEmpty();
var errors = req.validationErrors();
if(errors){
console.log(errors)
}
else {
var newUser = new User({
username:nam,
pass:pass
});
User.createUser(newUser,function(err,user){
if(err) throw err;
console.log(user);
});
res.location('/register');
res.redirect('/register');
}
I got this result when I run the code.
GET /register 304 25.699 ms - -
[ { param: 'nam', msg: 'Name is required', value: undefined },
{ param: 'pass', msg: 'Pass is required', value: undefined } ]
errorsreturning fromreq.validationErrors()? Isn't in an object?req.checkBodymethod, supposed to be the actual properties on thereq.bodyobject not the variable names i.e.req.checkBody('name', 'Name is required').notEmpty(); req.checkBody('userpass', 'Pass is required').notEmpty();