Quantcast
Channel: Javaonlineguide.net » validation
Viewing all articles
Browse latest Browse all 6

Javascript code to check password complexity | Validation for Strong Password with example

$
0
0

The following Javascript code is used to check whether the given password satisfies the following rules
1. Password should have at least 8 characters.
2. Password should have

        i) at least one upper case letter (A – Z).

        ii) at least one lower case letter(a-z).

        iii) At least one digit (0 – 9) .

        iv) at least one special Characters of !@#$%&*()

Depending upon number of rules satised, we can decide password complexity whether it is strong or medium or weak. (For eg. if all the rules satisfied , then the password is strong , …)

The following code gives alert message if any one of the above condition is not satisfied.
In two ways we can write the javascript code .

Method 1 -> Using Regular Expressions.

Method 2 -> Using simple javascript code.

//Method 1 using REGEX starts


function isStrongPwd1(password) {

        var regExp = /(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[!@#$%&*()]).{8,}/;

        var validPassword = regExp.test(password);

        return validPassword;

} 

//Method 1 ends here

//Method 2  starts heare

function isStrongPwd2(password) {

     var uppercase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

     var lowercase = "abcdefghijklmnopqrstuvwxyz";

     var digits = "0123456789";

     var splChars ="!@#$%&*()";

     var ucaseFlag = contains(password, uppercase);

     var lcaseFlag = contains(password, lowercase);

     var digitsFlag = contains(password, digits);

     var splCharsFlag = contains(password, splChars);

     if(password.length>=8 && ucaseFlag && lcaseFlag && digitsFlag && splCharsFlag)
           return true;
     else
           return false;

  }

function contains(password, allowedChars) {

    for (i = 0; i < password.length; i++) {

            var char = password.charAt(i);

             if (allowedChars.indexOf(char) >= 0) { return true; }

         }

     return false;
}

//Method 2 ends here

//Calling function starts here


function submitDetails()

{

      var password=document.testForm.password1.value;

      var message="The password must have atleast 8 chars with one uppercase letter, one lower case letter, one digit and one of !@#$%&amp;*()";

// Calling method1

      if(!isStrongPwd1(password)) {

           alert(message);

           success=false;

       }

// Calling method2

      if(!isStrongPwd2(password)) {

           alert(message);

           success=false;

      }

} 

//Calling function ends here

//Input form for password

<body>
<form name="testForm">
      <input type="password" name="password1" />
      <input type="submit" name="submitb" value="Submit" onClick="javascript:submitDetails()"/>
</form>
</body>

Viewing all articles
Browse latest Browse all 6

Trending Articles