Validate password strength in front-end

Asked

Viewed 690 times

2

Good evening, everyone,

I need to validate the password that will be typed in the input simultaneously to the typing of this, that is, I need to validate with javascritp. I have 3 Divs and texts that must have their color changed as the password specifications are reached (6 characters = Yellow, 6 characters between upper and lower case = orange, 6 characters between upper case, lower case and numbers = green)but I do not know how to validate this information.

Someone could help me?

<form>
      <div class="form-group">
        <label for="exampleInputEmail1">E-mail</label>
        <input type="email" class="form-control" id="exampleInputEmail1" aria-describedby="email">
      </div>
      <div class="form-group">
        <label for="senha">Senha</label>
        <input type="password" class="form-control" id="senha"></br>
        <div class="row" id="barras">
          <div id="barra" class="col-md-3"></div>
          <div id="barra_1" class="col-md-3"></div>
          <div id="barra_2" class="col-md-3"></div>
        </div>
      </div>
      <p>Pelo menos 6 caracteres</p>
      <p>Pelo menos 1 letra maiúscula</p>
      <p>Pelo menos 1 número</p></br>
      <div class="form-group">
        <label for="confirma_senha">Confirme sua senha</label>
        <input type="password" class="form-control" id="confirma_senha">
      </div>
      <button type="submit" class="btn btn-primary">Cadastrar</button>         
    </form>
  • What would be the function of these "slash"?

  • https://answall.com/q/58857/101

  • Check the input value with a regular expression and then show/hide or modify the class or color of a div

1 answer

1


Can validate using Regular Expressions, where:

/.{6,}/      → 6 caracteres ou mais
/[A-Z]{1,}/  → 1 letra maiúscula ou mais
/[0-9]{1,}/  → 1 número ou mais

I only modified your HTML by placing the sentences inside each div and changing the background color according to the criteria met by the above expressions.

I used an event oninput to listen when something is entered in the password field. This event will call the function val() that will validate the password.

I also used an event onsubmit which will detect when you try to submit it. This event will also query the function val(), who will return true if the password is valid and equal to the field confirmar_senha, or false, otherwise. If you return false the form will not be sent.

Look how it turned out:

document.addEventListener("DOMContentLoaded", function(){

   document.forms[0].onsubmit = function(e){
      return val(e);
   }

   senha.oninput = function(e){
      val(e);
   }

   function val(e){

      var passo, passo1, passo2,
      v = senha.value,
      cor = "#fff",
      e = e.type == "submit";
   
      // verifica se tem 6 caracteres ou mais
      if(v.match(/.{6,}/)){
         barra.style.backgroundColor = "#FFFEB5";
         passo = true;
      }else{
         barra.style.backgroundColor = cor;
         passo = false;
      }

      // verifica se tem ao menos uma letra maiúscula
      if(v.match(/[A-Z]{1,}/)){
         barra_1.style.backgroundColor = "#FFD27E";
         passo1 = true;
      }else{
         barra_1.style.backgroundColor = cor;
         passo1 = false;
      }

      // verifica de tem ao menus um número
      if(v.match(/[0-9]{1,}/)){
         barra_2.style.backgroundColor = "#D8FFCD";
         passo2 = true;
      }else{
         barra_2.style.backgroundColor = cor;
         passo2 = false;
      }

      // o formulário só será enviado pelo evento submit
      // e todos os passos devem ser verdadeiros para validar
      if(passo && passo1 && passo2 && v == confirma_senha.value && e){
         alert("Senha ok!");
         return true;
      }else if(e){
         alert("Senha inválida ou não conferem");
         return false;
      }
   }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<form action="pagina.php">
   <div class="form-group">
     <label for="exampleInputEmail1">E-mail</label>
     <input type="email" class="form-control" id="exampleInputEmail1" aria-describedby="email">
   </div>
   <div class="form-group">
     <label for="senha">Senha</label>
     <input type="password" class="form-control" id="senha"></br>
     <div class="row" id="barras">
       <div id="barra" class="col-md-3">Pelo menos 6 caracteres</div>
       <div id="barra_1" class="col-md-3">Pelo menos 1 letra maiúscula</div>
       <div id="barra_2" class="col-md-3">Pelo menos 1 número</div>
     </div>
   </div>
   <div class="form-group">
     <label for="confirma_senha">Confirme sua senha</label>
     <input type="password" class="form-control" id="confirma_senha">
   </div>
   <button class="btn btn-primary">Cadastrar</button>         
 </form>

Since you use Bootstrap, you can do the same thing using jQuery codes. In this case the difference is not too big:

$(document).ready(function(){
   
   $("form").submit(function(e){
      return val(e);
   });

   $(senha).on("input", function(e){
      val(e);
   });

   function val(e){

      var passo, passo1, passo2,
      v = senha.value,
      cor = "#fff", // cor padrão das divs
      e = e.type == "submit";
   
      // verifica se tem 6 caracteres ou mais
      if(v.match(/.{6,}/)){
         $(barra).css("background-color", "#FFFEB5");
         passo = true;
      }else{
         $(barra).css("background-color", cor);
         passo = false;
      }

      // verifica se tem ao menos uma letra maiúscula
      if(v.match(/[A-Z]{1,}/)){
         $(barra_1).css("background-color", "#FFD27E");
         passo1 = true;
      }else{
         $(barra_1).css("background-color", cor);
         passo1 = false;
      }

      // verifica de tem ao menus um número
      if(v.match(/[0-9]{1,}/)){
         $(barra_2).css("background-color", "#D8FFCD");
         passo2 = true;
      }else{
         $(barra_2).css("background-color", cor);
         passo2 = false;
      }

      // o formulário só será enviado pelo evento submit
      // e todos os passos devem ser verdadeiros para validar
      if(passo && passo1 && passo2 && v == $(confirma_senha).val() && e){
         alert("Senha ok!");
         return true;
      }else if(e){
         alert("Senha inválida ou não conferem");
         return false;
      }
   }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<form action="pagina.php">
   <div class="form-group">
     <label for="exampleInputEmail1">E-mail</label>
     <input type="email" class="form-control" id="exampleInputEmail1" aria-describedby="email">
   </div>
   <div class="form-group">
     <label for="senha">Senha</label>
     <input type="password" class="form-control" id="senha"></br>
     <div class="row" id="barras">
       <div id="barra" class="col-md-3">Pelo menos 6 caracteres</div>
       <div id="barra_1" class="col-md-3">Pelo menos 1 letra maiúscula</div>
       <div id="barra_2" class="col-md-3">Pelo menos 1 número</div>
     </div>
   </div>
   <div class="form-group">
     <label for="confirma_senha">Confirme sua senha</label>
     <input type="password" class="form-control" id="confirma_senha">
   </div>
   <button class="btn btn-primary">Cadastrar</button>         
</form>

I also removed the type="submit" of button, for he within the form is already of the type submit, you don’t have to declare that.

  • thank you very much, your tip helped a lot, I was able to adapt the idea to my needs and it worked.!

  • Legal Lucas!...

Browser other questions tagged

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