Email validation together with password with jQuery

Asked

Viewed 906 times

0

I need to put out an APB when "all’s well" on my form. The situation is that I need to check without the email has "@" 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 you’re kind of rolling around, validating one thing, locking into another, which is more wrong there?

NOTE: It is not a Ubmit, I am doing it in steps, step 1 you need to put the email and password, only when you agree the information you can pass to step 2, so I want to validate this way

  • I recommend you use this plugin: https://jqueryvalidation.org/ will help you with validation and much more work!

  • Jquery validation, for validation -> https://github.com/jquery-validation/jquery-validation Sweet Alert, for alert -> https://sweetalert.js.org/guides/

2 answers

2


1 - Here your running code and errors found!

  • Wrong filter with 2 @ (corrected to continue testing)
  • In the first if if all fields are null works ok.
  • Other situations in the first if Baubau.
  • On first parole } else if (!filtro.test(email)) { if you enter wrong email and other null fields also OK. Note: I put to give blue color on the borders of the email field in this conditional.
  • In the second else if if you enter correct email passes through the first if and other null fields will give as Deu tudo certo! because that parole } else if (senha === senha_confirma && filtro.test(email)) { is true or is, senha === senha_confirma password and password confirm nulls 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>
	<input size="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 - Example of correct validation

Placed $(document).ready(function() { in the script because you never know where the script was placed on the page, with this 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>

<input size="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>

  • @dvd made and without erring, hahaha : D

  • ixi, I edited over ;/

  • needed that flag no, just use Return;

  • 1

    @dvd I incremented the code!!!

1

Problem

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

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

Has a @ the more, and for this reason does not work properly. Regardless of this the logic that has 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 the senha is empty but the confirmation and email are not, will no longer mark them in red.

Which means next you’ll be testing email, even if this being empty:

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

And then test again 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 or the senha or the senha_confirma empty, which did not enter it in the first if.

Solution

A solution taking more or less the logic it has is to test each field separately and mark with the appropriate color, whether you are right or not. In order to be able to see if everyone is right also needs 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 memorizes if any field behind has errors and if it has failed to register successfully. Although this logic works,.

To get around this problem we can use arrays memorizing all the fields to be tested. This facilitates the application of the styles in bulk. In order to take advantage of this logic also errors can be saved 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 <input type="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 a lot of code duplication has been eliminated, making it smaller, easy to maintain and add other fields.

As 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 right.

Browser other questions tagged

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