Email validation with password with jQuery

0

I need to give you an alert when I give "all right" on my form. The situation is that I need to check without the email having "@" and "." and also along with this if the two password fields have equal values. Here's the code.

$("#passo2_cad").click(function() {

    email = $("#user_email").val();
    filtro = /^([\w-\.]+@@([\w-]+\.)+[\w-]{2,4})?$/;
    senha = $("#user_password").val();
    senha_confirma = $("#user_confirm_password").val();


    if (senha === '' && senha_confirma === '' && email === '') {
        $("#user_password").css({
            border: '2px solid red'
        })
        $("#user_confirm_password").css({
            border: '2px solid red'
        })
        $("#user_email").css({
            border: '2px solid red'
        })
        $("#user_email").css({
            border: '2px solid red'
        })
    } else if (!filtro.test(email)) {
        $("#user_email").css({
            border: '2px solid red'
        })
    } else if (senha === senha_confirma && filtro.test(email)) {
        $("#user_password").css({
            border: '2px solid #70e870'
        })
        $("#user_confirm_password").css({
            border: '2px solid #70e870'
        })
        $("#user_email").css({
            border: '2px solid #70e870'
        })
        alert("Deu tudo certo!");
    }

})

It's just that I'm kind of messing around, validating one thing, locking up another, what's wrong with it?

OBS: It's not a submit, I'm doing it in steps, step 1 you need to put the email and password, only when you agree to the information that you can move to step 2, so I want to validate that way

    
asked by anonymous 24.04.2018 / 20:37

2 answers

1

1 - Here your code is running and the errors found!

  • Wrong filter with 2 @ (fixed to continue testing)
  • At first if if all fields are null it works ok.
  • Other situations in the first% baubau%.
  • In the first conditional if if you enter wrong email and other invalid fields too OK. Note: I placed it to give blue color on the borders of the email field in this conditional.
  • In the second } else if (!filtro.test(email)) { if you type correct email goes through the first else if and other null fields will give as else if because this conditional Deu tudo certo! is true ie } else if (senha === senha_confirma && filtro.test(email)) { password and confirm password null are equal and email is correct.

$("#passo2_cad").click(function() {

    email = $("#user_email").val();
    filtro = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
    senha = $("#user_password").val();
    senha_confirma = $("#user_confirm_password").val();


    if (senha === '' && senha_confirma === '' && email === '') {
        $("#user_password").css({
            border: '2px solid red'
        })
        $("#user_confirm_password").css({
            border: '2px solid red'
        })
        $("#user_email").css({
            border: '2px solid red'
        })
        $("#user_email").css({
            border: '2px solid red'
        })
    } else if (!filtro.test(email)) {
        $("#user_email").css({
            border: '2px solid blue'
        })
    } else if (senha === senha_confirma && filtro.test(email)) {
        $("#user_password").css({
            border: '2px solid #70e870'
        })
        $("#user_confirm_password").css({
            border: '2px solid #70e870'
        })
        $("#user_email").css({
            border: '2px solid #70e870'
        })
        alert("Deu tudo certo!");
    }

})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><inputsize="42" value="" id="user_email" placeholder="Email">
	<input size="42" type="password" value="" id="user_password" placeholder="Senha">
	<input size="42" type="password" value="" id="user_confirm_password" placeholder="Confirma senha">
	<button id="passo2_cad">Verificar</button>

2 - Correct validation example

  

I put senha === senha_confirma in the script because you never know where the script was placed on the page, with that line you can put the script anywhere.

$(document).ready(function(){

   $("#passo2_cad").click(function(){
   
      var email = $("#user_email").val();
      // filtros
      var emailFilter=/^.+@.+\..{2,}$/;
      var ilegalChars= /[\(\)\<\>\,\;\:\\/\"\[\]]/
   
      var senha = $("#user_password").val();
      var senha_confirma = $("#user_confirm_password").val();
   
      if(!senha || !senha_confirma || !email){
         if(!(emailFilter.test(email))||email.match(ilegalChars)){
            $("#user_email").css('border', '2px solid red');
            alert("email incorreto!");
            $( "#user_email" ).focus();
            return;
         }else{
            $("#user_email").css('border', '2px solid #70e870');
         }
   
         if((!senha)||(senha.length<4)){
            $("#user_password").css('border', '2px solid red');
            $("#user_password").attr("placeholder", "Minimo de 4 caracteres!");
            $( "#user_password" ).focus();
            return;
         }else{
            $("#user_email").css('border', '2px solid #70e870');
         }
      
         if(senha_confirma){
            $("#user_confirm_password").css('border', '2px solid red');
            return;
         }else{
            $("#user_email").css('border', '2px solid #70e870');
         }
      }
   
      if(senha !== senha_confirma){
         $("#user_confirm_password").val("");
         $("#user_password").css('border', '2px solid red');
         $("#user_confirm_password").css('border', '2px solid red');
         $("#user_confirm_password").attr("placeholder", "senhas não conferem!");
         $( "#user_confirm_password" ).focus();
         return;
      }
   
      $('input[id^="user_"]').css('border', '2px solid #70e870');
      alert("Deu tudo certo!");
   
   });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><inputsize="42" value="" id="user_email" placeholder="Email">
<input size="42" type="password" value="" id="user_password" placeholder="Senha">
<input size="42" type="password" value="" id="user_confirm_password" placeholder="Confirma senha">
<button id="passo2_cad">Verificar</button>
    
25.04.2018 / 00:28
0

Problem

I begin by saying that the regex you are using to validate the email:

/^([\w-\.]+@@([\w-]+\.)+[\w-]{2,4})?$/

You have @ more, so it does not work correctly. Regardless of which logic you have it also does not work:

if (senha === '' && senha_confirma === '' && email === '') {

Here you are saying that if these 3 things happen at the same time then mark these fields in red. Which means that if senha is empty but the confirmation and email are not, it will no longer mark them in red.

What means that next will test the email , even if it can be empty:

...
} else if (!filtro.test(email)) {

And then re-test email with regex, and compare passwords:

} else if (senha === senha_confirma && filtro.test(email)) {

When in fact it is possible that the user had left either senha or senha_confirma empty, it did not enter the first if .

Solution

A solution that takes more or less logic is to test each field separately and mark it with the appropriate color, depending on whether it is right or not. In order to see if everyone is right you also need more logic.

Example:

//variavel para saber se algum não está correto
let erros = false; 

if (senha === '' || senha !== confirma_senha) {
    $("#user_password").css({
        border: '2px solid red'
    });
}
else {
    $("#user_password").css({
        border: '2px solid #70e870'
    });
    erros = true;
}

//falta aqui a mesma lógica para a confirmacao da senha
//que não coloquei para não ser extenso

if (email === '' || !email.test(filtro)) {
    $("#user_email").css({
        border: '2px solid red'
    });
}
else {
    $("#user_email").css({
        border: '2px solid #70e870'
    });
    erros = true;
}

if (erros === false){
    //tudo certo
}

In this example, the error variable remembers if any backward field has errors and if it does not register successfully. Although this logic works, and is somewhat similar to yours, it is very repetitive and doubles the code a lot.

To work around this problem we can use arrays by memorizing all the fields to be tested. This facilitates the application of styles in bulk. In order to take advantage of this logic also errors can be stored in an array:

//todos os campos existentes num array
const campos = [$("#user_email"), $("#user_password"), $("#user_confirm_password")];

$("#passo2_cad").click(function() {
    email = $("#user_email").val();
    filtro = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
    senha = $("#user_password").val();
    senha_confirma = $("#user_confirm_password").val();

    let erros = []; //erros agora é um array para os campos errados
    
    if (senha === '' || senha !== senha_confirma){
        erros.push($("#user_password")); //se errado adiciona ao array de erros
    }        
    if (senha_confirma === '' || senha_confirma !== senha){
        erros.push($("#user_confirm_password")); 
    }
    if (email === '' || !filtro.test(email)){
        erros.push($("#user_email"));
    }
    
    //marcar todos os campos a verde
    for (let campo of campos){
        campo.css({border: '2px solid #70e870'});
    }
    
    if (erros.length === 0){
        alert("Deu tudo certo!");
    }
    else { //não deu certo, logo marca os errados a vermelho
        for (let campoErrado of erros){
            campoErrado.css({border: '2px solid red'});
        }
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>Email<inputtype="email" id="user_email"><br>
Password <input type="password" id="user_password"><br>
Confirmação <input type="password" id="user_confirm_password"><br>
<input type="submit" value="Cadastrar" id="passo2_cad">

In this scenario, much of the code duplication has been eliminated, making it smaller, easier to maintain, and adding other fields.

As a next step, it will be important to put the information of what went wrong in each step of the validation, so that the user does not get lost trying to find what did not work.

    
24.04.2018 / 23:31