Empty input after submitting form

Asked

Viewed 401 times

3

Hello, I am developing a login system, but I would like to improve something. When I register a user, and type his name, address, etc., and request the form, he returns all empty inputs. As in the GIF below...

Notice on the GIF above that after I press on Register, the inputs go blank. That would be the point. I don’t want the inputs to be empty.

Well, below follows the excerpt of the code I used. I use Passport.js to authenticate the user.

    passport.use('local.signup', new localStrategy({
       usernameField: 'email',
       passwordField: 'password',
       passReqToCallback: true
    }, function(req, email, password, done){
       req.checkBody('email', 'E-mail inválido').notEmpty().isEmail();
       req.checkBody('password', 'Insira uma senha').notEmpty();
       req.checkBody('password', 'Senha inválida').isLength({ min: 5 }).withMessage('Senha deve ter no mínimo 5 caracteres').equals(req.body.password1).withMessage('Senhas não conferem');

    var errors = req.validationErrors();

    if(errors) {
        var messages = [];
        errors.forEach(function(error){
            messages.push(error.msg);
        });
        return done(null, false, req.flash('error', messages));
    }

    User.findOne({'email': email}, function(err, user){
        if(err) {
            return done(err);
        }
        if(user) {
            return done(null, false, {message: 'Email já está sendo usado!'});
        }
        var newUser = new User();
            newUser.email = email;
            newUser.password = newUser.encryptPassword(password);
            newUser.save(function(err, result){
                if(err) {
                    return done(err);
                }
                return done(null, newUser);
            });
    });
}));
  • I’ve had this doubt, you handle the password difference on the right server side, one way out is to treat this difference on the client side with javascript using click event or something similar. Another way out is to treat the difference on the server but send the data back to the page and work the insertion of this data with if().

  • This "register" button would happen to be type='submit' ? Post your html and javascript too please.

  • That’s right. It’s a common HTML form. I already put it in the code here.

1 answer

3


We could, when rendering the page, send an object that through a script within the engine of view, check if there are values and fill them in the equivalent field. Thus, when submitting the form and returning the error, the inputs would be filled with the values of this object.

For example:

if (errors) {
  let valoresInput = {
    nome: req.body.nome,
    email: req.body.email
  };

  res.render('admin/form_add_noticia.ejs', { 
    showErrors: errors,  // enviamos os erros
    field: valoresInput  // informamos os campos preenchidos
  });

  return;
}

So, in your HTML form, with this code sent by the EJS view engine, I check and fill the input fields with object field which contains the values stored at the time the form was submitted.

<form action="/admin/login" method="POST">
  <input type="text" name="nome" value="<%= field.nome %>">
  <br>
  <input type="email" name="email" value="<%= field.email %>">
</form>

Observe:

  • <%= field.nome %> for the input of nome;
  • <%= field.email %> for the input of email.

Where <%= %> represents an EJS engine script that will print a value in this field.

In short, you have to send the body of the back request and fill in the fields automatically preventing them from being empty.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.