Search code examples
javascriptjqueryhtmlclient-side-validation

How to Check Password validation dynamically using jquery/javascript?


Kindly read my question fully before assign my one as duplicate. Hi I tried to verify password dynamically during keypress. Actually it is working for me while enter the password. But When I delete the password only 2 conditions satisfies. My code and images below:

My password box html code is

 <div class="form-group has-feedback">
 <input class="form-control" id="NewPassword" placeholder="New Password"  onkeypress="EnterPassword()" onkeydown="DeletePassword()" type="password">
 <span class="glyphicon glyphicon-lock form-control-feedback"></span>
 </div>

I used glyphicon-remove infront of each conditions for the password. When I enter the password each icon change to glyphicon-ok if the condition satisfies.

These are my password conditions with icon: enter image description here

Lets assume my password as Password@123, it contains all my required things, so all the icons changed to ok. enter image description here

But when I delete the password only 2 of the conditions satisfied. enter image description here

Codes for the function below:

 <script type="text/javascript" >
           function EnterPassword() {
            $("#NewPassword").keyup(function () {
            var regex1 = new Array();
            var regex2 = new Array();
            var regex3 = new Array();
            var regex4 = new Array();
                regex1.push("[A-Z]"); //Uppercase Alphabet.
                regex2.push("[a-z]"); //Lowercase Alphabet.
                regex3.push("[0-9]"); //Digit.
                regex4.push("[!@@#$%^&*]"); //Special Character.
     if ($(this).val().length>6) {
      $("#Length").removeClass("glyphicon glyphicon-remove").addClass("glyphicon glyphicon-ok");
    }

    for (var i = 0; i < regex1.length; i++) {
    if (new RegExp(regex1[i]).test($(this).val())) {
     $("#UpperCase").removeClass("glyphicon glyphicon-remove").addClass("glyphicon glyphicon-ok");
     }
     }
     for (var i = 0; i < regex2.length; i++) {
     if (new RegExp(regex2[i]).test($(this).val())) {
      $("#LowerCase").removeClass("glyphicon glyphicon-remove").addClass("glyphicon glyphicon-ok");
     }
     }
    for (var i = 0; i < regex3.length; i++) {
    if (new RegExp(regex3[i]).test($(this).val())) {
     $("#Numbers").removeClass("glyphicon glyphicon-remove").addClass("glyphicon glyphicon-ok");
     }
     }
     for (var i = 0; i < regex4.length; i++) {
     if (new RegExp(regex4[i]).test($(this).val())) {
     $("#Symbols").removeClass("glyphicon glyphicon-remove").addClass("glyphicon glyphicon-ok");
     }
      }
     });
     }

function DeletePassword() {
 $("#NewPassword").keyup(function () {
var regex1 = new Array();
var regex2 = new Array();
 var regex3 = new Array();
 var regex4 = new Array();
                regex1.push("[A-Z]"); //Uppercase Alphabet.
                regex2.push("[a-z]"); //Lowercase Alphabet.
                regex3.push("[0-9]"); //Digit.
                regex4.push("[!@@#$%^&*]"); //Special Character.
     var thisVal =$(this).val();

  if ($(this).val().length<6) {
 $("#Length").removeClass("glyphicon glyphicon-ok").addClass("glyphicon glyphicon-remove");
   }

for (var i = 0; i < regex1.length; i++) {
 if (new RegExp(regex1[i]).test(!thisVal)) {
  $("#UpperCase").removeClass("glyphicon glyphicon-ok").addClass("glyphicon glyphicon-remove");
   }
    }
 for (var i = 0; i < regex2.length; i++) {
  if (new RegExp(regex2[i]).test(!thisVal)) {
  $("#LowerCase").removeClass("glyphicon glyphicon-ok").addClass("glyphicon glyphicon-remove");
   }
  }
for (var i = 0; i < regex3.length; i++) {
  if (new RegExp(regex3[i]).test(!thisVal)) {
 $("#Numbers").removeClass("glyphicon glyphicon-ok").addClass("glyphicon glyphicon-remove");
    }
 }
  for (var i = 0; i < regex4.length; i++) {
 if (new RegExp(regex4[i]).test(!thisVal)) {
   $("#Symbols").removeClass("glyphicon glyphicon-ok").addClass("glyphicon glyphicon-remove");
    }
 }
  });
  }
    </script>

NOTE: UpperCase,LowerCase,Numbers,Symbols are the Id name that I gave to the tag where I used the glyphicon remove icon. If my codes not working completely means my question may comes under duplicate. But Its Partially working, So kindly let me know if there is any mistake I did on my code.

Thanks in Advance


Solution

  • We can simplify your code a lot.

    For a start instead of using inline event handlers we will use jQuery's .on to bind the event.

    Next we'll consolidate your rules into a JSON object array with the rules target.

    We then iterate the Regex based rules adding and removing classes as required

    /*Actual validation function*/
    function ValidatePassword() {
      /*Array of rules and the information target*/
      var rules = [{
          Pattern: "[A-Z]",
          Target: "UpperCase"
        },
        {
          Pattern: "[a-z]",
          Target: "LowerCase"
        },
        {
          Pattern: "[0-9]",
          Target: "Numbers"
        },
        {
          Pattern: "[!@@#$%^&*]",
          Target: "Symbols"
        }
      ];
    
      //Just grab the password once
      var password = $(this).val();
    
      /*Length Check, add and remove class could be chained*/
      /*I've left them seperate here so you can see what is going on */
      /*Note the Ternary operators ? : to select the classes*/
      $("#Length").removeClass(password.length > 6 ? "glyphicon-remove" : "glyphicon-ok");
      $("#Length").addClass(password.length > 6 ? "glyphicon-ok" : "glyphicon-remove");
      
      /*Iterate our remaining rules. The logic is the same as for Length*/
      for (var i = 0; i < rules.length; i++) {
    
        $("#" + rules[i].Target).removeClass(new RegExp(rules[i].Pattern).test(password) ? "glyphicon-remove" : "glyphicon-ok"); 
        $("#" + rules[i].Target).addClass(new RegExp(rules[i].Pattern).test(password) ? "glyphicon-ok" : "glyphicon-remove");
          }
        }
    
        /*Bind our event to key up for the field. It doesn't matter if it's delete or not*/
        $(document).ready(function() {
          $("#NewPassword").on('keyup', ValidatePassword)
        });
    .glyphicon-remove {
      color: red;
    }
    
    .glyphicon-ok {
      color: green;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <div class="form-group has-feedback">
      <input class="form-control" id="NewPassword" placeholder="New Password" type="password">
      <span class="glyphicon glyphicon-lock form-control-feedback"></span>
    </div>
    <div id="Length" class="glyphicon glyphicon-remove">Must be at least 7 charcters</div>
    <div id="UpperCase" class="glyphicon glyphicon-remove">Must have atleast 1 upper case character</div>
    <div id="LowerCase" class="glyphicon glyphicon-remove">Must have atleast 1 lower case character</div>
    <div id="Numbers" class="glyphicon glyphicon-remove">Must have atleast 1 numeric character</div>
    <div id="Symbols" class="glyphicon glyphicon-remove">Must have atleast 1 special character</div>