簡體   English   中英

Javascript驗證中的正則表達式

[英]Regular expression in Javascript validation

我對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的建議更進一步的最新更新 *用戶名/密碼驗證

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

我認為,制作一個正則表達式來驗證密碼是否符合您的所有規則是一個錯誤,這有兩個原因。

  1. 將來更改規則將是一項繁重的工作
  2. 您將無法告訴最終用戶他們違反了哪一部分。 如果他們忘記添加數字,則不能說“您需要添加至少一個數字”。 相反,您只能說驗證失敗“無效密碼”。

我建議為每個規則使用單獨的簡單正則表達式,然后遍歷它們,收集一系列違反規則的錯誤,然后立即為用戶提供所有規則。 這將是更好的用戶體驗,並使您的驗證工作變得更加容易。

更新:這是我的想法:

<!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(){...不正確。 如果沒有關鍵字“功能”,那么您將無法使用該功能。 另外,由於您是通過內聯click事件來觸發函數的,因此您無需執行此onload,也不需要在下一行中執行click事件監聽器,因此我也刪除了該事件。
  • 這些行:

    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>

您的代碼包含很多語法錯誤。

  • 這個:

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

    應該是:if(pwd.test(password)&&(user.test(username))&&(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)) 

您頁面上的另一個錯誤:

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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM