Email and password validation using Keyup

Asked

Viewed 289 times

4

I am using the code that tells me if both emails are identical, if both passwords are identical and if they are at least 8 and at most 10 characters long. And only if the emails were equal, passwords equal and in the correct size does the form sign up button appear.

But how did I manage to use only the keyup in the email2 and senha2, if the user comes back and enters something in the password or email, does not change to error the input.

What I wanted to know was how to put the same event with the same rules keyup of email2 and senha2 also in the email and senha, to be validated in both confirmation fields.

And note that I haven’t even been able to restrict and validate the email, only whether or not they are identical.

$('#email2').on('keyup', function () {
    var email = $("#email").val();
    var email2 = $("#email2").val();

    if (email != email2) {
        $("#message").html("Os email não são identicos").css('color', 'red');
        $('#validator').prop('disabled' , true);
    } else {
        $("#message").html("Os email são identicos").css('color', 'green');
        $('#validator').prop('disabled' , true);
    }
    $('#validator').prop('disabled' , true);
    $('#senha2').on('keyup', function (){
        var password = $("#senha").val();
        var confirmPassword = $("#senha2").val();
        if (password.length < 8 || password.length  > 16) { 
            $("#divCheckPassword2").html("As senhas precisam ter no minimo 8 caracteres e no máximo 16").css('color', 'red');
            $('#validator').prop('disabled' , true);
        } else {
            $("#divCheckPassword2").html("").css('color', 'green');
            $('#validator').prop('disabled' , true);
        }

        if (password != confirmPassword) {
             $("#divCheckPassword").html("As senhas não são").css('color', 'red');
             $('#validator').prop('disabled' , true);
        } else {
            $("#divCheckPassword").html("Senhas identicas").css('color', 'green');
            $('#validator').prop('disabled' , true);
        }

        if (password != confirmPassword ||  password.length < 8 || 
            password.length  > 16 || email != email2){
            $('#validator').prop('disabled' , true);
        } else {
            $('#validator').prop('disabled' , false);
        }
    })
});

2 answers

4

You can do this way, the code has been explained through the comments.

//Iniciar script somente depois de carregar todo o html(dom)
$(function(){

  $('#validator').prop('disabled', true);

  //Separa a validação de e-mail
  function validarEmail(){
  
    var email = $("#email");
    var email2 = $("#email2");
  
    if (email.val() != email2.val()) {
      $("#message").html("Os email não são identicos").css('color', 'red');
      $('#validator').prop('disabled', true);
    } else {
      $("#message").html("Os email são identicos").css('color', 'green');
      $('#validator').prop('disabled', true);
    }
  }

  //Separa a validação de senha
  function validarSenha(){
  
    var senha = $("#senha");
    var senha2 = $("#senha2");
    
    var minLength = 8;
    var maxLength = 10;
    
    if (senha.val().length < minLength || senha.val().length > maxLength) {
      $("#divCheckPassword2").html("As senhas precisam ter no minimo " + minLength + " caracteres e no máximo " + maxLength).css('color', 'red');
      $('#validator').prop('disabled', true);
    }
    else {
      $('#validator').prop('disabled', true);
      $("#divCheckPassword2").html("" + minLength + " caracteres e no máximo " + maxLength).css('color', 'green');
    }
    
    if (senha.val() != senha2.val()) {
      $("#divCheckPassword").html("As senhas não são iguais").css('color', 'red');
      $('#validator').prop('disabled', true);
    } else {
      $("#divCheckPassword").html("Senhas identicas").css('color', 'green');
      $('#validator').prop('disabled', true);
    }
  }
  
  /**
  * Os eventos foram separados, já que o evento keyup da "senha2" 
  * só funcionária caso o evento de "email2" fosse acionado 
  * em conjunto, o que não aconteceria 
  *
  * Assim você chama a função em qualquer elemento adicionando
  * os eventos que desejar, e ao alterar o código de alguma regra
  * esta mudança será somenta na função reponsável pela aquela
  * validação.
  */
  
  $('#email').on('keyup', function() {
    validarEmail();
    validarSenha();
  });

  $('#senha').on('keyup', function() {
    validarEmail();
    validarSenha();
  });
  
  $('#email2').on('keyup', function() {
    validarEmail();
    validarSenha();
  });

  $('#senha2').on('keyup', function() {
    validarEmail();
    validarSenha();
  });

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="validator">
  <div id="validator">

  </div>
  <div id="divCheckPassword">

  </div>
  <div id="divCheckPassword2">

  </div>  
</div>

<div>
    <label for="email">E-mail:</label>
    <input type="email" id="email" name="email">
</div>

<div>
    <label for="email2">Confirmar e-mail:</label>
    <input type="email" id="email2" name="email2">
</div>
<div>
    <label for="senha">Senha (minimo 8 e máximo 10):</label>
    <input type="password" id="senha" name="senha"
           minlength="8" required>
</div>

<div>
    <label for="senha2">Confirmar senha (minimo 8 e máximo 10):</label>
    <input type="password" id="senha2" name="senha2"
           minlength="8" required>
</div>

  • Thanks friend, but now it does not validate the password, even if it has more than 8 characters and are identical, for everything in the error part of passwords

  • right gave perfect, more like validate now this part with it codeFunction validar(){ if (email != Email2.val() || password.val().length < 8 || password.val().length > 16 || password.val() != password2.val()){ $('#Validator'). prop('disabled', true); }Else { $('#Validator'). prop('disabled' , false); } }code

  • I didn’t touch the validation part, just the events, copy its validation, but anyway, I’ll change it :)

  • I can only thank your help friend

  • I edited and now this working validation

  • 1

    thank you very much friend, saved my life

  • @Sam, I put "separate" taking into account the original code, where he put a keyup inside another keyup.

Show 2 more comments

3


I think you can separate events for each type of validation: email and password:

$('#email, #email2').on('keyup', validarEmail); // chama a função ref. ao email
$('#senha, #senha2').on('keyup', validarSenha); // chama a função ref. à senha

And use a function to control the sign-up button:

function valida(){

   $('#validator')
   .prop('disabled', val_email && val_senha && val_senha2 ? false : true);

}

This function will be called in the events keyup and will only enable the button if the 3 variables (val_email, val_senha and val_senha2) were true.

Another detail is the button already comes with the disabled attribute in HTML:

<button id="validator" disabled>Cadastrar</button>
                          ↑

See example:

$(function(){

   // declaro variáveis de controle
   var val_email, val_senha, val_senha2;
   
   function valida(){
      
      $('#validator')
      .prop('disabled', val_email && val_senha && val_senha2 ? false : true);
      
   }

   function validarEmail(){
  
      var email = $("#email").val().trim();
      var email2 = $("#email2").val().trim();

      // só irá verificar se os campos tiverem algo  
      if(email && email2){
         if(email != email2){

            $("#message")
            .html("Os emails não são idênticos")
            .css('color', 'red');
            val_email = false;

         }else{

            $("#message")
            .html("Os emails são idênticos")
            .css('color', 'green');
            val_email = true;

         }

         // chama a função de controle do botão
         valida();

      }

   }

   function validarSenha(){

      var senha = $("#senha").val();
      var senha2 = $("#senha2").val();

      // só irá verificar se os campos tiverem algo
      if(senha && senha2){
    
         if(senha.length < 8 || senha.length > 10){
   
            $("#divCheckPassword2")
            .html("As senhas precisam ter no mínimo 8 caracteres e no máximo 10")
            .css('color', 'red');
            val_senha = false;
   
         }else{
   
            $("#divCheckPassword2")
            .html("8 caracteres e no máximo 10")
            .css('color', 'green');
            val_senha = true;
   
         }
       
         if(senha != senha2){
   
            $("#divCheckPassword")
            .html("As senhas não são iguais")
            .css('color', 'red');
            val_senha2 = false;
   
         }else{
   
            $("#divCheckPassword").html("Senhas idênticas")
            .css('color', 'green');
            val_senha2 = true;
         }
         
         // chama a função de controle do botão
         valida();

      }
   }
  
   $('#email, #email2').on('keyup', validarEmail);
   $('#senha, #senha2').on('keyup', validarSenha);

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
E-mail: <input type="email" id="email" autofocus>
<br>
Confirmar e-mail: <input type="email" id="email2">
<br>
<div id="message"></div>
<br><br>
Senha: <input type="password" id="senha">
<br>
Confirmar senha: <input type="password" id="senha2">
<br>
<div id="divCheckPassword"></div>
<div id="divCheckPassword2"></div>
<br>
<button id="validator" disabled>Cadastrar</button>

  • I really liked your logic, but I changed the code up there, if I had used tbm to see if the email is valid, and adding this check to activate the sign-up button, would be like?

  • You could do it this way: https://jsfiddle.net/mohqz12k/

  • friend, I became your fan, perfect!!!!!!

Browser other questions tagged

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