Empty input after submitting form

2

Hello, I'm developing a login system, but I'd like to improve something. When I register a user, and type their name, address, etc., and make the request of the form, it returns all the empty inputs. Like the GIF below ...

Notice in the above GIF that after I hit Register , the inputs are left blank . That would be the point. I do not want the inputs to be empty.

Well, below is the snippet of 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);
            });
    });
}));
    
asked by anonymous 10.10.2018 / 00:11

1 answer

1

vode should, when rendering the page, send an object through a script inside the view engine, check if there are values and fill in the field. So 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, field: valoresInput});
  return;
 }

Soon in your html form, with this code allowed by the EJS view engine, I check and fill in the fields of the input with field object that 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>

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

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

    
09.11.2018 / 04:32