Home > Software engineering >  Checking if password contains symbols as well DOES NOT WORK
Checking if password contains symbols as well DOES NOT WORK

Time:11-14

In Javascript I tried to add a function like this for checking if the entered password contains any symbol (special) character such as !@#$%^&*()_ \-=\[\]{};':"\\|,.<>\/?.

So I did this:

        function checkpasswordlength(){
            var format1 = /^[!@#$%^&*()_ \-=\[\]{};':"\\|,.<>\/?]*$/;
            var e = document.getElementById("password").value;
            if(e != "") {
                if(e.length >= 12){
                    if(e.match(format1)){
                        document.getElementById("passwordstrengthstatus").style.display = "inline";
                        document.getElementById("passwordstrengthstatus").innerHTML = "strong";
                        document.getElementById("passwordstrengthstatus").style.setProperty('background-color', '#3cb878', 'important');
                    }else{
                        document.getElementById("passwordstrengthstatus").style.display = "inline";
                        document.getElementById("passwordstrengthstatus").innerHTML = "normal";
                        document.getElementById("passwordstrengthstatus").style.setProperty('background-color', '#3cb878', 'important');
                    }
                }else{
                    document.getElementById("passwordstrengthstatus").style.display = "inline";
                    document.getElementById("passwordstrengthstatus").innerHTML = "weak";
                    document.getElementById("passwordstrengthstatus").style.setProperty('background-color', 'red', 'important');
                }
            }else{
                document.getElementById("passwordstrengthstatus").style.display = "none";
            }
        }

As you can see, it will check if the password is not empty and it's length is more than 12 characters, then go ahead and check for e.match(format1).

But the problem is, when I enter those characters as well, it will not return this condition as true and therefore the message strong does not appear and still shows normal message on screen.

So what's going wrong with this?

How can I solve this problem and properly check if the string contains the written symbols or not?

CodePudding user response:

If you just want to check for the presence of at least one symbol character, then remove the ^ and $ anchors and just use:

var format1 = /[!@#$%^&*()_ \=\[\]{};':"\\|,.<>\/?-]/;

Note that the hyphen has been moved to the end of the character class. If you want to stick with your original pattern and match the entire password, then modify to this:

var format1 = /^.*[!@#$%^&*()_ \=\[\]{};':"\\|,.<>\/?-].*$/;

CodePudding user response:

Your current regex matches only if the password contains nothing but special characters. try adding a-zA-Z0-9 inside too

^[a-zA-Z0-9!@#$%^&*()_ \-=\[\]{};':"\\|,.<>\/?]*$

  • Related