Node.js (express) Form is cleared upon submission

I am working on a truly basic registration form in Node.js (using Express), and I'm trying to find the easiest way to provide basic form validation. I went with the Express Validator, which seems to do just fine. However, my goal is simply to show any required verification messages, and leave the values โ€‹โ€‹entered by the user on their own.

The request information does not seem to return it in res.render, which I think makes sense. However, I searched everywhere that I can think of, and I canโ€™t find the links that discuss how to save the filled field fields after error messages appear.

Below is a small snippet describing my approach:

post: function(req, res){ var userName = req.body.username; var password = req.body.password; //Validate input req.assert("username", 'Invalid email address.').isEmail(); req.assert("password", 'Password cannot be empty.').notEmpty(); req.assert("passwordConfirm", 'Passwords entered do not match!').equals(password); //Make sure we have no validation errors var pageErrors = req.validationErrors(); if(!pageErrors) { userModel.CreateUser(userName, password, function(err){ if(err) { //there was a problem inserting new user... probably already exists //will need to check the error to confirm var dbErrorMessage = "Could not insert record into database!"; if(err.code === 11000) { //this is a duplicate entry dbErrorMessage = "A user with that email address already exists!"; } res.render('register.html', { pageErrors: [{msg: dbErrorMessage }]}); } else { res.render('register.html', { successMessage: successMessage }); } }); } else { res.render('register.html', { pageErrors: pageErrors }); } 
+8
validation express
source share
6 answers

Unfortunately, you need to re-fill the form manually. If you get any page errors, you will return the form values โ€‹โ€‹to the view.

  if(!pageErrors) { // ... } else { res.render('register.html', { pageErrors: pageErrors, userName: userName }); } 

And, in your opinion, you would do a simple check to see if they have any errors and redistribute them accordingly. You will need to keep track of which errors are generated for each form field.

 <% if (userNameError) { %> <input type="text" name="userName" value="<%- userName %>" /> <% } else { %> <input type="text" name="userName" /> <% } %> 

Another popular way is to submit the form using ajax to the server and complete all your validations. If an error occurs, the data of the entered form remains, and you will see an error, otherwise redirect after successful login. Below is an example of how to submit a form using javascript.

 $("#login-button").live("submit", function (e) { // this will prevent the form from being uploaded to the server the conventioanl way e.preventDefault(); // the form data var data = $(this).serialize(); // this logs the user in $.ajax({ type: 'POST', url: BASE_URL + '/login', data: data, dataType: 'json', success: function (data, status) { // successful }, }); // superfluous fallback return false; }); 
+10
source share

There is an easy way to use

 app.use(express.bodyParser()) and app.use(expressValidator()); 

You can use req.body

 res.render('register.html', { pageErrors: pageErrors, validated: req.body }); 

And I'm not sure which template language you use, but you can do something like.

 <input type="text" name="userName" value="<%= pageErrors.userName.value || validated.userName %>" /> 

This then returns good input if ok or bad input if it needs to be fixed.

+5
source share

You can do this using connect-flash

Below are the code fragments in different files to return the values โ€‹โ€‹entered by the user into the form when the checks are not performed when registering with the passport.

Run this command below to add a new package to package.json

 npm install connect-flash --save 

app.js

 var flash = require('connect-flash'); app.use(flash()); // add this above passport initialize app.use(passport.initialize()); app.use(passport.session()); 

config / passport.js (Please focus on loading form data into flash)

 passport.use('local.signup', new LocalStrategy({ usernameField: 'email', passwordField: 'password', passReqToCallback: true }, function (req, email, password, done) { req.checkBody('first_name', 'Firstname is missing').notEmpty(); req.checkBody('last_name', 'Lastname is missing').notEmpty(); req.checkBody('email', 'Invalid email').notEmpty().isEmail(); req.checkBody('password', 'Password is too short. Minimum size is 6.').notEmpty().isLength({min:6}); req.checkBody('confirm_password', 'Password and confirm password didn\'t not match').equals(req.body.password); var errors = req.validationErrors(); if (errors) { var messages = []; errors.forEach(function(error) { messages.push(error.msg); }); req.flash('formdata', req.body); // load form data into flash return done(null, false, req.flash('error', messages)); } User.findOne({'email': email}, function (err, user) { if (err) { req.flash('formdata', req.body); // load form data into flash return done(err); } if (user) { req.flash('formdata', req.body); // load form data into flash return done(null, false, {message: 'Email is already in use.'}); } var newUser = new User(); newUser.first_name = req.body.first_name; newUser.last_name = req.body.last_name; newUser.email = email; newUser.password = newUser.encryptPassword(password); newUser.save(function(err, result) { if (err) { return done(err); } return done(null, newUser); }); }); })); 

routes / index.js (Please focus on the form data in flash loaded back into the variable)

  router.get('/signup', function (req, res, next) { var messages = req.flash('error'); var formdata = req.flash('formdata'); // Get formdata back into a variable res.render('user/signup', {csrfToken: req.csrfToken(), messages: messages, // pass it here to access in view file hasErrors: messages.length > 0, formData: formdata[0] }); }); router.post('/signup', passport.authenticate('local.signup', { badRequestMessage: 'Please fill the form with all details', failureRedirect: '/user/signup', failureFlash: true }), function (req, res, next) { if (req.session.oldUrl) { var oldUrl = req.session.oldUrl; req.session.oldUrl = null; res.redirect(oldUrl); } else { res.redirect('/user/profile'); } }); 

views / signup.hbs (Please focus on the values โ€‹โ€‹in the input elements)

 <form class="wow fadeInUp animated" data-wow-delay=".7s" action="/user/signup" method="post" > <input type="text" placeholder="First Name" name="first_name" value="{{ formData.first_name }}"> <input type="text" placeholder="Last Name" name="last_name" value="{{ formData.last_name }}"> <input type="text" class="email" placeholder="Email Address" name="email" value="{{ formData.email }}"> <input type="password" name="password" value="" class="lock" placeholder="Password"> <input type="password" name="confirm_password" value="" class="lock" placeholder="Confirm Password"> <input type="hidden" name="_csrf" value="{{ csrfToken }}"> <input type="submit" name="Register" value="Register"></form> 

Hope this helps.

+3
source share

set a variable for all input, e.g.

 var inputData = { firstname : req.body.firstname, lastname : req.body.lastname, email : req.body.email, username : req.body.username, password : req.body.password, password_confirmation : req.body.password_confirmation, agreetoterms: req.body.agreetoterms } 

and then pass this variable to the view

 res.render('register.html', { pageErrors: [{msg: dbErrorMessage }], inputData: inputData }); 

then in your view

 value="<%= inputData.userName %>" 
0
source share

if you use jade and form Validator from npm, the best part is that you can use the if statement in jade and then you just check if there is an error with res.render, we also send objects. See This

 if(errors){ res.render('register',{ errors : errors, name : name, email : email, username : username, password : password, password2 : password2 }); 

And in jade you do it

 input.form-control(name='name',type='text',placeholder='Enter Name',value = (errors ? '#{name}':'')) 

therefore, if the error value is set to a variable in the name that will be displayed when sending back

I think you can also do this in Angular2 / Angular.js

0
source share

check out http://www.quietless.com/kitchen/building-a-login-system-in-node-js-and-mongodb/

on register.html do it

  var data = {}; data.user = $('#user-input').val(); data.email = $('#email-input').val(); data.pass = $('#pass-input').val(); $.ajax({ url: '/signup' , type: 'POST' , data: JSON.stringify(data) , contentType: 'application/json' , dataType: 'html' }) .done(function(data) { if (data == 'ok') { $('#content').html('You are registered!'); } else $('#account-form-container').append('<br>error:' + data); }); 

Errors such as: CAN NOT POST /

in this case, the author of the tutorial using the link above uses lib $ .ajaxForm

you can also use https://github.com/felixge/node-formidable

or $ ('# myform'). submit () replace with $ ('# submit-a-link'). click ()

-one
source share

All Articles