Javascript验证中的正则表达式

时间:2011-10-08 15:34:56

标签: javascript

我对javascript很新,并且一直在使用正则表达式。我正在尝试创建一个简单的密码/用户名验证表单。我相信我的正则表达式是错误的,在某些地方我搞砸了我的语法,因为这不会运行。谁能告诉我我做错了什么?感谢。

这是我的代码:

 <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>

*编辑***

<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>

** 这是最新更新,让Jason的建议更进一步 < EM> *                        用户名/密码验证

  <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>

3 个答案:

答案 0 :(得分:2)

在我看来,制作单个正则表达式以验证密码是否符合您的所有规则是错误的,原因有两个。

  1. 未来改变规则将是一项艰巨的工作
  2. 您无法告诉最终用户他们违反了哪个部分。如果他们忘了添加一个数字,你就不能说“你需要添加至少一个数字”。相反,您只能说验证失败“密码无效”。
  3. 我建议为每个规则使用一个单独的,简单的正则表达式,然后通过它们收集一系列违反规则的错误,然后立即向用户提供所有这些规则。这将是一个更好的用户体验,并将使您的验证工作更多更容易。

    更新:这就是我的想法:

    <!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>
    

    更新:我正在更新我的答案,为用户提供满足其需求的其他解决方案。

    我从上面第3个更新的脚本所做的更改是:

    • 行window.onload = check(){...不正确。如果没有关键字“function”,您就无法使用它来运行它。此外,由于您使用内联单击事件触发该函数,因此您不需要执行此onload,也不需要在以下行上单击事件侦听器,因此我也删除了它。
    • 行:

      var errorList = document.getElementById(“errors”);

      errorList.innerHTML ='';

    导致语法错误,因为div'错误'不再存在,因此不需要它们。

    • 我更新了最后一部分而不是向上发送警报消息 在表单上方整齐地显示消息。不知道你为什么这么做 想要这个,但好的。你可能至少想进去做那些更整洁的东西。

    希望这有帮助

    <!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>
    

答案 1 :(得分:1)

您的代码包含很多语法错误。

  • 此:

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

    应该是:     if(pwd.test(password)&amp;&amp;(user.test(username))&amp;&amp;(password == passwordAgain))

  • 此:

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

    应该是:

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

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

    应该是:

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

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

    应该是:

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

答案 2 :(得分:0)

页面上还有一个错误:

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

应该是:

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

请记住,在文本中使用单引号(')时,请始终使用(\')。


您的网页上仍然存在多个编码语法错误,但它们无法显示所有这些错误。提高JavaScript技能的一种简单方法是安装FireBug,然后学习如何使用它。

您对代码进行评论的习惯非常好,只需学会使用/ tab字符编写代码,以使代码更清晰。可读的。

以下是我为您编辑的代码,只需将它们与原始代码进行比较即可找出错误:

<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>
相关问题