JavaScript test password strength

From Regex Regular Expression Encyclopedia

Jump to: navigation, search

This wiki is for replacing tab characters in a string with a different character using JavaScript. In this recipe, we use a pipe (|) to replace the tab.

[edit] Code

<html>
<head>
<title></title>
</head>
<body>
<form name="form1">
    <input type="textbox" name="txtInput" />
    <script type="text/javascript">
    function validate() {
        if (! document.form1.txtInput.value.match(/^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9]).{7,15}$/)) {
            alert("Please enter valid value!")
        } else {
            alert("Success!")
        }
    }
    </script>
    <input type="button" name="btnSubmit" onclick="validate()" value="Go" />
</form>
</body>
</html>

[edit] How It Works

The look-arounds in the expression make it seem more complicated than it really is. At the heart of the expression, without the look-arounds, is the following:

Regular Expression Description
^ at the beginning of the line, followed by . . .
. any character.
{7,15} found anywhere from seven to fifteen times, followed by . . .
$ the end of the line.

Now let's add the look-arounds, which are grouped by the expressions (?= and ). Three of them exist in this expression: (?=.*[A-Z]), (?=.*[a-z]), and (?=.*[0-9]). These look-arounds say, "This expression must appear somewhere to the right.” In this case, that’s to the right of ^, which is the line anchor that anchors the beginning of the line. The first look-ahead matches anything followed by a capital letter ([A-Z]), the second matches anything followed by a lowercase letter ([a-z]), and the third matches anything followed by a number ([0-9]).

[edit] Variations

This one has many variations, but probably the most notable is to make the expression more complicated by adding a fourth look-ahead group that matches punctuation characters, such as (?=.*[!@#$%^&*()]).

Another variation is to use a different character class for the number, such as \d if the flavor of regular expressions you’re using supports it.

Personal tools