1

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 } ]
2
  • What is the value of errors returning from req.validationErrors()? Isn't in an object? Commented Jan 4, 2019 at 8:35
  • Wrong parameters passed in the req.checkBody method, supposed to be the actual properties on the req.body object not the variable names i.e. req.checkBody('name', 'Name is required').notEmpty(); req.checkBody('userpass', 'Pass is required').notEmpty(); Commented Jan 4, 2019 at 8:44

1 Answer 1

1

The code below should work, I think the main issue is to use the actual form variable names (name, userpass):

index.js

const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const expressValidator = require('express-validator');

app.use(express.static('./'));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(expressValidator());

var router = express.Router();
app.use("/", router);

router.post('/register', function(req, res, next) {
    console.log('/register POST body: ', req.body);

    /* Check form variables. */
    req.checkBody('name', 'Name is required').notEmpty();
    req.checkBody('userpass', 'Pass is required').notEmpty();

    var errors = req.validationErrors();
    if (errors) {
        console.error("Validation errors occurred: ", errors);
        res.status(400).json({ status: "Bad Request" });
        return;
    }

    console.log("Validation successful");

    // Get user input from register form
    let nam = req.body.name;
    let pass = req.body.userpass;

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

app.listen(3000);

index.html

<!doctype html>
<html lang="en">
    <body>
    <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>
    </body>
</html>
Sign up to request clarification or add additional context in comments.

1 Comment

Cool, glad to hear that!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.