3

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

5
  • on you onkeydown of the input you have already defined the function DeletePassword() then why are you again calling the keyup inside the function it will be called on the keydown event no need to call the keyup inside or is there any special need for it. And the same goes for EnetrPassword(). Commented Aug 29, 2018 at 5:15
  • You are involving keyup event in the keydown event. I don't see the usability of the arrays and loop s. Simple if statements will do the job. Try to avoid inline event handlers as much as possible. Commented Aug 29, 2018 at 5:58
  • @ths,@vikscool :So far from your comments I understand that keydown and keypress event was assigned to a functions in the html code, then no need to use the keyup inside the functions, but once I removed the keyup functions within the delete and enter functions, the thing is not working(even for enter password). Commented Aug 29, 2018 at 6:27
  • do you have any errors in the console ? Commented Aug 29, 2018 at 6:29
  • I dont have any errors so far.. while running my above code, entering password working properly.. while delete password, I want the icon to change back from right to wrong, but 2 of 5 conditions only satisfies and icons changed.. Commented Aug 29, 2018 at 6:40

2 Answers 2

6

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>

Sign up to request clarification or add additional context in comments.

5 Comments

Woww.. your one work like awesome.. Thank you so much.. I already have the CSS and html codes rdy.. Now I used ur functions.. I will go through target, pattern soon.. what is the main use of this target pattern ?
The Target is the div that will be updated, Pattern is the regex pattern that is used to see if the password meets that complexity rule. rules is just an array of these objects. Here is a quick bit of info on objects
I used your one and its working for me. At the same time, I wanna know what I did wrong in my code.? Do you find any mistakes in my code...Coz Its partially working right so I am asking
I didn't go through it in depth. One thing that stood out is .test(!thisVal) . This doesn't work. What you want instead is if (!(new RegExp(regex4[i]).test(thisVal))). You need to negate the result of the test, not the value being tested.
Thank you so much once again.. Its working if I change my code as per ur above comment.. But I put that one as alternative one and I am currently using your target pattern method. Thank you once again.
1

i give you simple example.

Html

<!DOCTYPE HTML>
<html>
<head>
<title>Password strength checker in jQuery</title>
<link href='http://fonts.googleapis.com/css?family=Source+Sans+Pro|Open+Sans+Condensed:300|Raleway' rel='stylesheet' type='text/css'>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script><!-- jQuery Library-->
<link rel="stylesheet" href="css/passwordscheck.css" /><!-- Include Your CSS file here-->
<script src="js/passwordscheck.js"></script><!-- Include Your jQUery file here-->
</head>
<body>
<div id="container">
<div id="header">
<h2>Password Strength Checking with jQuery</h2>
<hr>
</div>
<div id="content">
<form id="register">
<label for="password"><b>Password : </b></label>
<input name="password" id="password" type="password" placeholder="Type Your Password here"/>&nbsp;&nbsp;
<span id="result"></span>
</form>
</div>
</div>
</body>
</html>

JS

$(document).ready(function() {
$('#password').keyup(function() {
$('#result').html(checkStrength($('#password').val()))
})
function checkStrength(password) {
var strength = 0
if (password.length < 6) {
$('#result').removeClass()
$('#result').addClass('short')
return 'Too short'
}
if (password.length > 7) strength += 1
// If password contains both lower and uppercase characters, increase strength value.
if (password.match(/([a-z].*[A-Z])|([A-Z].*[a-z])/)) strength += 1
// If it has numbers and characters, increase strength value.
if (password.match(/([a-zA-Z])/) && password.match(/([0-9])/)) strength += 1
// If it has one special character, increase strength value.
if (password.match(/([!,%,&,@,#,$,^,*,?,_,~])/)) strength += 1
// If it has two special characters, increase strength value.
if (password.match(/(.*[!,%,&,@,#,$,^,*,?,_,~].*[!,%,&,@,#,$,^,*,?,_,~])/)) strength += 1
// Calculated strength value, we can return messages
// If value is less than 2
if (strength < 2) {
$('#result').removeClass()
$('#result').addClass('weak')
return 'Weak'
} else if (strength == 2) {
$('#result').removeClass()
$('#result').addClass('good')
return 'Good'
} else {
$('#result').removeClass()
$('#result').addClass('strong')
return 'Strong'
}
}
});

Reference : Link one of the best example for you i hope you understand.

1 Comment

Thank you for your one and your link too. But I used this method already for comparing two password. I want some exact answers for Icon changing things. Now I got the ans .Thank you once again

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.