1

I'm working on a registrations page in express.js (using mongodb on serverside) and working on the validations part. My user.js looks something like this -

router.post('/register', [
check('firstname', 'Please enter your first name').exists().trim().escape().not().isEmpty(),
check('lastname', 'Please enter your last name').exists().trim().not().isEmpty(),
check('email', 'Please enter an email').exists().trim().not().isEmpty(),
check('usn', 'Please enter USN').exists().trim().not().isEmpty(),
check('usn', 'USN should be 10 characters long').isLength({ max: 10, min: 10 }),
check('usn', 'USN must be entered in Uppercase').isUppercase(),
check('course', 'Please enter Course').exists().trim().not().isEmpty(),
check('password', 'Please enter password').exists().trim().not().isEmpty(),
check('password').matches(/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z0-9]).{8,}$/, 
"i").withMessage("Password should be a combination of one uppercase , one lower case, one special 
char, one digit and min 8 , max 20 char long"),




], (req, res) => {
const err = validationResult(req);
if (!err.isEmpty()) {

req.flash("messages", { user: 'error', err: err.errors[0].msg });
res.locals.messages = req.flash();
res.render('register', { user: 'error', err: err.errors[0].msg });



} else {
userreg.register(
  // eslint-disable-next-line new-caperr
  new userreg({
    firstname: req.body.firstname,
    lastname: req.body.lastname,
    username: req.body.email,
    usn: req.body.usn, // validate so that no space is taken or else request modal wont work
    course: req.body.course,

  }),
  req.body.password,
  (err) => {
    if (err) {
      console.log(err);
      // res.render('register', { user: 'error' });
    } else {
      res.render('submit-success', { username: req.body.firstname });
    }
  })
};
});


module.exports = router;

with my app.js as follows -

//flash-messages

app.use(function (req, res, next) {
res.locals.messages = req.flash();
next();
});

and my register.ejs like this -

          <!--alert-->
          <% if (user == 'error') { %>

          <div class="alert alert-warning" role="alert">
            <%= err %>
          </div>

I am fairly new to expressjs and has just started with simple form validations. All the validations are working fine along with respective flash messages. But everytime the flash message is displayed , it renders the entire user.js page and erases all the data in the other textboxes. Is there a particular way in which i can display flash messages without affecting the textboxes without forcing users to fill the form again from beginning and only correcting the particular field for which a flash message is raised?

Thank you in advance.

Mahesh m
  • 39
  • 1
  • 8

0 Answers0