简体   繁体   中英

Regular expression in Javascript validation

I'm very new to javascript and have been playing around with regular expressions. I'm trying to create a simple password/username validation form. I believe my regular expressions are wrong and somewhere I messed up with my syntax because this won't run. Could anyone tell me what I did wrong? Thanks.

Here is my code:

 <html>

 <head>

 <title>Username/Password Validation</title>

 <script type="text/javascript">

 function check(username, password, passwordAgain)
 {
// at least one number, one lowercase and one uppercase letter 
// at least six - ten characters that are letters, numbers or the underscore 
var pwd = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])\w{6,10}$/;

// at least six - ten characters that are letters, numbers or the underscore 
//the first character CANNOT start with a digit
var user = /^!=.*\d\w{6,10}$/;

if (pwd.test(password)) && (user.test(username)) && (password == passwordAgain)
{
alert("Passed Validation");
}
else if (password != passwordAgain)
{
alert(Your passswords don't match.");
}
else if !(pwd.test(password)) && !(user.test(username))
{
alert(username + password + " Your password and username are not valid.");
}
else if !(pwd.test(password)) && (user.test(username))
{
alert(password + " This password is not valid.");
}
else
{
alert(username +" This username is not valid.");
}


 </script>
 </head>

 <body>

 <form>

 <h3> Username-Password Validation </h3>

<ul>
<li> The username must be between 6 and 10 characters long. </li>
<li> The username must contain only letters and digits. </li>
<li> The username cannot begin with a digit. </li>
<li> The password and the repeat password must match. </li>
<li> The password must be between 6 and 10 characters. </li>
<li> The password must contain only letters and digits. </li>
<li> The password must have at least one lower case letter,<br /> at
 least one upper case letter, and at least one digit. </li>
</ul>


Username: <input type = 'text' id = 'username' /> <br />

Password: <input type = 'text' id = 'password' /> <br />

Reenter Password: <input type = 'text' id = 'passwordAgain' /> <br/> 

<p>

<input type ='button' onclick='check(username, password, passwordAgain )' value='Submit' />

<input type ='reset' value='Clear' /> 

</p>

</form>

</body>

</html>

*EDIT***

<html>
<head>
 <title>Username/Password Validation</title>

 <script type="text/javascript">
    function check(username, password, passwordAgain){
        //List of possible error messages
        var errorList = '';

        // at least six - ten characters that are letters, numbers or the underscore
        var sixtotencharacters = /\w{6,10}$/;

        // at least one number, one lowercase and one uppercase letter 
        var oneofeach = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])/;

        //first character does not start with digit
        var firstDigit = /^!=.*\d/;

        //Begin validation

        if (sixtotencharacters.test(password) && sixtotencharacters.test(username)  && oneofeach.test(password) && firstDigit.test(username) && password == passwordAgain)
           {
            alert("Passed Validation");
    }
        else
        {
         if (password != passwordAgain){
            errorlist = 'Your passswords don\'t match. ';
        }if (!sixtotencharacters.test(username)){
            errorlist = errorlist + 'Username needs to be six to ten characters. ';
        }if (!sixtotencharacters.test(password)){
            errorlist = errorlist + 'Password needs to be six to ten characters. ';
        }if (!oneofeach.test(password)){
            errorlist = errorlist + 'You need to have at least one number, one lowercase and one uppercase letter. ';
        }if (!firstDigit.test(username)){
            errorlist = errorlist + 'First character of username can\'t be a digit. ';
        }
    alert(errorlist);

    }
   </script>
</head>

<body>

<form>

<h3> Username-Password Validation </h3>

<ul>
<li> The username must be between 6 and 10 characters long. </li>
<li> The username must contain only letters and digits. </li>
<li> The username cannot begin with a digit. </li>
<li> The password and the repeat password must match. </li>
<li> The password must be between 6 and 10 characters. </li>
<li> The password must contain only letters and digits. </li>
<li> The password must have at least one lower case letter,<br /> at
 least one upper case letter, and at least one digit. </li>
</ul>


Username: <input type = 'text' id = 'username' /> <br />

Password: <input type = 'text' id = 'password' /> <br />

Reenter Password: <input type = 'text' id = 'passwordAgain' /> <br/> 

<p>

<input type ='button' onclick='check(username, password, passwordAgain )' value='Submit' />

<input type ='reset' value='Clear' /> 

</p>

</form>

</body>

</html>

** This is the most recent update that takes Jason's suggestions a step further * Username/Password Validation

  <script>
    window.onload = check() {
        document.getElementById('btnSubmit').addEventListener('click', check() {
            var errors = [];
            var username = document.getElementById('username').value;
            var password = document.getElementById('password').value;
    var passwordAgain = document.getElementById('passwordAgain').value;
            var errorList = document.getElementById("errors");

            errorList.innerHTML = '';

    if (password != passwordAgain) { errors.push("Your passwords do not match") }

            var hasNumber = password.match(/\d+/);

            if (hasNumber == null) { errors.push("You did not include a number in your password") }

            var hasUpper = password.match(/[A-Z]+/);

            if (hasUpper == null) { errors.push("You did not include an Uppercase Letter in your password") }

            var hasLower = password.match(/[a-z]+/);

            if (hasLower == null) { errors.push("You did not include an Lowercase Letter in your password") }

    var hasAtleast6lessThan10password = password.length < 6 || password.length > 10; 

    if (hasAtleast6lessThan10password) { errors.push("Your password must be at least 6 characters long and cannot be more than 10") } 

            var hasAtleast6lessThan10username = username.length < 6 || username.length > 10;

            if (hasAtleast6lessThan10username) { errors.push("Your username must be at least 6 characters long and cannot be more than 10") } 

            var firstCharacterNotDigit = username.match(/^[^\d]/);

            if (firstCharacterNotDigit == null) { errors.push("Your username may not begin with a number") }  

            if (errors.length > 0) {

                for (var i = 0; i < errors.length; i++) {
                    var errorElem = document.createElement("li");
                    errorElem.innerHTML = errors[i];

                    errorList.appendChild(errorElem);
                }
            }

        });
    };
</script>


</head>

<body>

<form>

<h3> Username-Password Validation </h3>

<ul>
<li> The username must be between 6 and 10 characters long. </li>
<li> The username must contain only letters and digits. </li>
<li> The username cannot begin with a digit. </li>
<li> The password and the repeat password must match. </li>
<li> The password must be between 6 and 10 characters. </li>
<li> The password must contain only letters and digits. </li>
<li> The password must have at least one lower case letter,<br /> at
 least one upper case letter, and at least one digit. </li>
</ul>


Username: <input type = 'text' id = 'username' size="10" /> <br />

Password: <input type = 'text' id = 'password' size="10"/> <br />

Reenter Password: <input type = 'text' id = 'passwordAgain' size="10" /> <br/> 

<p>

<input type ='button' onclick='check()' value='Submit' />

<input type ='reset' value='Clear' /> 

</p>

</form>

</body>

</html>

Making a single regex to validate that a password meets all of your rules, in my opinion, is a mistake, for two reasons.

  1. Changing rules in the future will be a huge chore
  2. You make it impossible for you to be able to tell your end user which part they violated. If they forget to add a number you can't say "You need to add at least one numeral". Instead you can only say that the validation failed "Invalid password".

I recommend having a separate, simple regex for each rule and just run through them collecting an array of errors of violated rules, then provide the user with all of them at once. This will be a better user experience and will make your validation work much easier.

Update: Here is what I am thinking:

<!DOCTYPE html> 
<html>
<head>
<meta charset="UTF-8">
<title>Password Checking with JavaScript</title>
    <script>
        window.onload = function() {
            document.getElementById('btnSubmit').addEventListener('click', function() {
                var errors = [];
                var username = document.getElementById('username').value;
                var password = document.getElementById('password').value;
                var errorList = document.getElementById("errors");

                errorList.innerHTML = '';

                var hasNumber = password.match(/\d+/);

                if (hasNumber == null) { errors.push("You did not include a number in your password") }

                var hasUpper = password.match(/[A-Z]+/);

                if (hasUpper == null) { errors.push("You did not include an Uppercase Letter in your password") }

                var hasLower = password.match(/[a-z]+/);

                if (hasLower == null) { errors.push("You did not include an Lowercase Letter in your password") }

                var hasAtleast8lessThan10 = username.length < 6 || username.length > 10;

                if (hasAtleast8lessThan10) { errors.push("You username must be at least 8 characters long and cannot be more than 10") }  


                var fisrtCharacterNotDigit = username.match(/^[^\d]/);

                if (fisrtCharacterNotDigit == null) { errors.push("Your username may not begin with a number") }  

                if (errors.length > 0) {

                    for (var i = 0; i < errors.length; i++) {
                        var errorElem = document.createElement("li");
                        errorElem.innerHTML = errors[i];

                        errorList.appendChild(errorElem);
                    }
                }

            });
        };
    </script>
</head> 
<body> 
    <ul id="errors"></ul>
    <input type="textbox" name="username" id="username" size="3">
    <input type="textbox" name="password" id="password" size="3">
    <button id="btnSubmit" >Check Password</button>
</body>
</html>

Update: I am updating my answer to give the user an additional solution that meets his needs.

The changes I made from your 3rd updated script above are:

  • The line window.onload = check() {... is incorrect. Without the keyword 'function' you are not giving it a function to work with. Also, since you are triggering the function with a click event inline you do not need to do this onload, nor did you need the click event listener on the following line, so I removed that as well.
  • The lines:

    var errorList = document.getElementById("errors");

    errorList.innerHTML = '';

were causing a syntax error because the div 'errors' no longer exists, so they were not needed.

  • I updated the final part to throw an alert message up instead of displaying the messages neatly above the form. Not sure why you would want this, but OK. You'll probably at least want to go in and make those neater.

Hope this helps

<!DOCTYPE html > 
<html>
    <head>
        <meta charset="UTF-8">
        <title>Password Checking with JavaScript</title>

        <script>
            function check() {
                var errors = [];
                var username = document.getElementById('username').value;
                var password = document.getElementById('password').value;
                var passwordAgain = document.getElementById('passwordAgain').value;

                if (password != passwordAgain) { errors.push("Your passwords do not match") }

                var hasNumber = password.match(/\d+/);

                if (hasNumber == null) { errors.push("You did not include a number in your password") }

                var hasUpper = password.match(/[A-Z]+/);

                if (hasUpper == null) { errors.push("You did not include an Uppercase Letter in your password") }

                var hasLower = password.match(/[a-z]+/);

                if (hasLower == null) { errors.push("You did not include an Lowercase Letter in your password") }

                var hasAtleast6lessThan10password = password.length < 6 || password.length > 10; 

                if (hasAtleast6lessThan10password) { errors.push("Your password must be at least 6 characters long and cannot be more than 10") } 

                var hasAtleast6lessThan10username = username.length < 6 || username.length > 10;

                if (hasAtleast6lessThan10username) { errors.push("Your username must be at least 6 characters long and cannot be more than 10") } 

                var firstCharacterNotDigit = username.match(/^[^\d]/);

                if (firstCharacterNotDigit == null) { errors.push("Your username may not begin with a number") }  

                if (errors.length > 0) {
                    alert(errors.join('\r\r'));
                }
            };
        </script>


    </head>

    <body>

            <form>

            <h3> Username-Password Validation </h3>

            <ul>
            <li> The username must be between 6 and 10 characters long. </li>
            <li> The username must contain only letters and digits. </li>
            <li> The username cannot begin with a digit. </li>
            <li> The password and the repeat password must match. </li>
            <li> The password must be between 6 and 10 characters. </li>
            <li> The password must contain only letters and digits. </li>
            <li> The password must have at least one lower case letter,<br /> at
             least one upper case letter, and at least one digit. </li>
            </ul>


            Username: <input type = 'text' id = 'username' size="10" /> <br />

            Password: <input type = 'text' id = 'password' size="10"/> <br />

            Reenter Password: <input type = 'text' id = 'passwordAgain' size="10" /> <br/> 

            <p>

            <input type ='button' onclick='check()' value='Submit' />

            <input type ='reset' value='Clear' /> 

            </p>

            </form>

    </body>
</html>

Your code contains a lot syntax errors.

  • This:

     if (pwd.test(password)) && (user.test(username)) && (password == passwordAgain) 

    should be: if (pwd.test(password) && (user.test(username)) && (password == passwordAgain))

  • This:

     alert(Your passswords don't match."); 

    should be:

     alert("Your passswords don't match."); 
  • This:

     else if !(pwd.test(password)) && !(user.test(username)) 

    should be:

     else if (!pwd.test(password) && !user.test(username)) 
  • This:

     else if !(pwd.test(password)) && (user.test(username)) 

    should be:

     else if (!pwd.test(password) && user.test(username)) 

One more error on your page :

errorlist = errorlist + 'First character of username can't be a digit. ';

should be :

errorlist = errorlist + 'First character of username can\'t be a digit. ';

Remember when using a single quote (') inside the text, always use (\\') instead.


There are still several coding syntax errors on your page, but it's effectless showing all of them. A simple way for you to improve you JavaScript skill is to install FireBug then learn how to use it.

Your habit to comment the code is very good, just learn to write your code with the /tab character to make your code more clearly & readable.

Below is the code that I've edited for you, just compare them to your original code to figure out the mistake:

<html>
    <head>
     <title>Username/Password Validation</title>

    <script type="text/javascript">
        function check(username, password, passwordAgain){
            //List of possible error messages
            var errorList = '';

            // at least six - ten characters that are letters, numbers or the underscore
            var sixtotencharacters = /\w{6,10}$/;

            // at least one number, one lowercase and one uppercase letter 
            var oneofeach = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])/;

            //first character does not start with digit
            var firstDigit = /^!=.*\d/;

            //Begin validation
            if (password != passwordAgain){
                alert("Your passswords don't match.");
            }else if (!sixtotencharacters.test(username)){
                errorlist = 'Username needs to be six to ten characters. ';
            }else if (!sixtotencharacters.test(password)){
                errorlist = errorlist + 'Password needs to be six to ten characters. ';
            }else if (!oneofeach.test(password)){
                errorlist = errorlist + 'You need to have at least one number, one lowercase and one uppercase letter. ';
            }else if (!firstDigit.test(username)){
                errorlist = errorlist + 'First character of username can\'t be a digit. ';
            }else{
                alert("Passed Validation");
            }
        }
    </script>
</head>

<body>

<form>

<h3> Username-Password Validation </h3>

<ul>
<li> The username must be between 6 and 10 characters long. </li>
<li> The username must contain only letters and digits. </li>
<li> The username cannot begin with a digit. </li>
<li> The password and the repeat password must match. </li>
<li> The password must be between 6 and 10 characters. </li>
<li> The password must contain only letters and digits. </li>
<li> The password must have at least one lower case letter,<br /> at
 least one upper case letter, and at least one digit. </li>
</ul>


Username: <input type = 'text' id = 'username' /> <br />

Password: <input type = 'text' id = 'password' /> <br />

Reenter Password: <input type = 'text' id = 'passwordAgain' /> <br/> 

<p>

<input type ='button' onclick='check(username, password, passwordAgain )' value='Submit' />

<input type ='reset' value='Clear' /> 

</p>

</form>

</body>

</html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM