Password validation using regular expression in jQuery

Last Reply on Nov 07, 2016 09:27 AM By dharmendr

Posted on Nov 07, 2016 01:51 AM

 

<script type="text/javascript">
function PasswordValidator() {
     var passwordvalid = /^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#\$%\^&\*])$/;
     var passwordstrength = document.getElementById("<%=txtPassword.ClientID%>");
     if (passwordstrength != passwordvalid)
     {
         alert("Password must contain at least 1 capital letter,\n\n1 small letter, 1 number and 1 special character.\n\nFor special characters you can pick one of these -,(,!,@,#,$,),%,<,>");
         return false;
      }
}
</script>
<asp:TextBox ID="txtPassword" runat="server" TextMode="Password"></asp:TextBox>
<asp:Button ID="btnCheck" runat="server" OnClientClick="PasswordValidator()" position: absolute; width: 90px;" Text="Check" />

Hi guys,

I was trying to create a function, which would check if the value inside txtPassword meets the password regex requirement. When a button is clicked and if the value fails, it would pop the alertbox shown. So I entered Will123! as a password to test it and the alertbox came up. “W” is capital letter. Could you please tell me what is wrong with the function. I need the alertbox to pop only if the password doesn’t meet the regex.

Thank you for your time.

Posted on Nov 07, 2016 09:27 AM
 
Refer the below code.
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <script type="text/javascript">
            function PasswordValidator() {
                var passwordstrength = document.getElementById("<%=txtPassword.ClientID%>");
                var regex = new Array();
                regex.push("[A-Z]"); //Uppercase Alphabet.
                regex.push("[a-z]"); //Lowercase Alphabet.
                regex.push("[0-9]"); //Digit.
                regex.push("[!@#$%^&*]"); //Special Character.

                var passed = 0;
                for (var i = 0; i < regex.length; i++) {
                    if (new RegExp(regex[i]).test(passwordstrength.value)) {
                        passed++;
                    }
                }

                if (passed > 3) {
                    alert("Valid");
                }
                else {
                    alert("Password must contain at least 1 capital letter,\n\n1 small letter, 1 number and 1 special character.\n\nFor special characters you can pick one of these -,(,!,@,#,$,),%,<,>");
                    return false;
                }
            }
        </script>
        <input name="txtPassword" type="password" id="txtPassword" />
        <input type="submit" name="btnCheck" value="Check" onclick="PasswordValidator();"
            id="btnCheck" style="position: absolute; width: 90px;" />
    </div>
    </form>
</body>
</html>

Demo