繁体   English   中英

如何对密码输入进行强力验证并确认密码输入

[英]How to do a strong validation of password entry and validate confirm password entry

我有一些HTML和Javascript,要求用户使用以下规则输入密码:

  1. 至少8个字符
  2. 至少1个大写字母
  3. 至少1个小写字母
  4. 至少1个特殊字符
  5. 至少1个数字字符

随后是密码确认条目。 密码和密码确认输入下面有div块,其中包含p标记中包含的错误消息,当发生任何错误时,该错误消息应该变得可见。 它似乎不起作用。

我还在此CSHTML文件中使用C#Razor代码,因此需要在字符串中使用“ @@”而不是@。 如果我对此有误,请告诉我。

密码:(必须至少包含1个小写字母字符,1个大写字母字符,1个特殊字符,1个数字字符和至少8个字符)

        <input type="password" name="password_admin1_create" oninput="return validate_password()"><br><br>
        <script>
            var password = document.getElementsByName("password_admin1_create")[0];
            function validatePassword(val) {
                var strongRegex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@@#\$%\^&\*])(?=.{8,})/;
                console.log(re.test(val))
                return strongRegex.test(val);
            }

            function validate_password() {
                if (validatePassword(password.value)) {
                    document.getElementById("password_result_invalid").style.visibility = "hidden";
                    document.getElementById("password_result_invalid").style.height = "0";
                } else {
                    document.getElementById("password_result_invalid").style.visibility = "visible";
                    document.getElementById("password_result_invalid").style.height = "initial";
                }
            }
        </script>
        <div id="password_result_invalid" class="error_verify">
            <p style="color:red">Invalid password format.</p>
        </div>

        <p>Please confirm the password:</p>
        <input type="password" name="password_admin1_create_confirm" oninput="return validate_password_confirm()"><br><br>
        <script>
            var password_confirm = document.getElementsByName("password_admin1_create_confirm")[0].value;
            var password = document.getElementsByName("password_admin1_create")[0].value;

            function validate_password_confirm() {
                if (password_confirm == password) {
                    document.getElementById("password_confirmation_invalid").style.visibility = "hidden";
                    document.getElementById("password_confirmation_invalid").style.height = "0";
                } else {
                    document.getElementById("password_confirmation_invalid").style.visibility = "visible";
                    document.getElementById("password_confirmation_invalid").style.height = "initial";
                }
            }
        </script>
        <div id="password_confirmation_invalid" class="error_verify">
            <p style="color:red">Passwords do not match.</p>
        </div>

我的猜测是此表达式可能有效:

^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[?!%@#$%^&*])[A-Za-z0-9?!%@#$%^&*]{8,}$

我们将添加开始和结束锚点,并删除其中一些转义符。

regex101.com的右上角对表达式进行了说明,如果您希望对其进行探索/简化/修改,并且在此链接中 ,您可以根据需要观看它与某些示例输入的匹配方式。

 const regex = /^(?=.*[az])(?=.*[AZ])(?=.*[0-9])(?=.*[?!%@#$%^&*])[A-Za-z0-9?!%@#$%^&*]{8,}$/gm; const str = `Az0^AAAA Az0^AAA Az0^AAAAA`; let m; while ((m = regex.exec(str)) !== null) { // This is necessary to avoid infinite loops with zero-width matches if (m.index === regex.lastIndex) { regex.lastIndex++; } // The result can be accessed through the `m`-variable. m.forEach((match, groupIndex) => { console.log(`Found match, group ${groupIndex}: ${match}`); }); } 

您应该将“ pattern”属性分配给任何适合您密码要求的正则表达式。 例如:

<  input type="password" id="psw" name="psw" 
pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}" 
title="Must contain at least one number and one uppercase and lowercase letter, and at least 8 or more characters" 
required >

该链接可能也有帮助: https : //www.w3schools.com/howto/howto_js_password_validation.asp

我几周前做了这个。 只需发布它,看看它是否可以为您提供帮助(我知道这不是最干净的一种)

HTML

所有要求都显示在上方,并且最初是红色的。

<div class="requirements">
    <ul>
        <li id="length" class="red">Include at least 8 digits and three special characters</li>
        <li id="uppercase" class="red">Include at least one upper case characters (A-Z)</li>
        <li id="lowercase" class="red">Include at least one lower case character (a-z)</li>
        <li id="numbers" class="red">Include a number (0-9)</li>
        <li id="symbols" class="red">Include a symbol (!, #, $, etc.)</li>
    </ul>
</div>

JS

将按键事件处理程序添加到当前页面上的输入字段:

var inputfields = document.forms["changePasswordForm"].getElementsByTagName("input");
for (var i = 0; i < inputfields.length; i++){
    inputfields[i].addEventListener('keyup', function(e){
        // On every key up, check the password
        var password = document.getElementById('sf_guard_user_password');
        validatePassword(password.value);
    })
}

最后我的(丑陋的)验证密码功能

function validatePassword(password) {

                // Minimum 8 characters
                if (password.length > 7) {
                    document.getElementById('length').classList.remove('red');
                    document.getElementById('length').classList.add('green');
                } else {
                    document.getElementById('length').classList.remove('green');
                    document.getElementById('length').classList.add('red');
                }

                // At least one uppercase
                if (/[A-Z]/.test(password)) {
                    document.getElementById('uppercase').classList.remove('red');
                    document.getElementById('uppercase').classList.add('green');
                } else {
                    document.getElementById('uppercase').classList.remove('green');
                    document.getElementById('uppercase').classList.add('red');
                }

                // At least one lowercase
                if (/[a-z]/.test(password)) {
                    document.getElementById('lowercase').classList.remove('red');
                    document.getElementById('lowercase').classList.add('green');
                } else {
                    document.getElementById('lowercase').classList.remove('green');
                    document.getElementById('lowercase').classList.add('red');
                }

                // At least one number
                if (/[0-9]/.test(password)) {
                    document.getElementById('numbers').classList.remove('red');
                    document.getElementById('numbers').classList.add('green');
                } else {
                    document.getElementById('numbers').classList.remove('green');
                    document.getElementById('numbers').classList.add('red');
                }

                // At least one symbol
                if (/[$@$!%*#?&]/.test(password)) {
                    document.getElementById('symbols').classList.remove('red');
                    document.getElementById('symbols').classList.add('green');
                } else {
                    document.getElementById('symbols').classList.remove('green');
                    document.getElementById('symbols').classList.add('red');
                }

            }

最后,我正在检查是否满足所有要求:

document.getElementById('changePasswordForm').addEventListener('submit',  function(e){
    e.preventDefault();
    // Once again ugly because length is fixed
    if (document.getElementsByClassName('green').length > 4) {
        document.getElementById('changePasswordForm').submit();
    }
})

我不知道这是否对您有帮助。 但是我试过了:)

使用模式正则表达式:

  1. 至少8个字符
  2. 至少1个大写字母
  3. 至少1个小写字母
  4. 至少1个特殊字符
  5. 至少1个数字字符

"^(?=.*[az])(?=.*[AZ])(?=.*\\d)(?=.*[@$!%*?&])[A-Za-z\\d@$!%*?&]{8,}$"

用法:

<input type="password" name="pw" pattern="^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$" title="Strong Password">

您不断看到Invalid password format.的原因Invalid password format. 是您首先创建一个变量:

var password = document.getElementsByName("password_admin1_create")[0];

然后,再次创建它,将其直接设置为值( 为empty

var password = document.getElementsByName("password_admin1_create")[0].value;

因此,可变密码将始终为空,并且永远不会通过正则表达式检查。

注意

也此变量password_confirm被直接设置为空,并且在console.log(re.test(val))没有re

关于图案

您可以对模式进行一些小的调整:

  • 前瞻(?=.{8,})断言右边的字符是任何char的8倍以上,这还将匹配一个空格。
  • 您可以对其进行更新,以使用字符类来仅匹配允许匹配的字符,并使用锚点$声明字符串的结尾。
  • 该模式可以利用对比度来断言例如不是数字,然后是数字。

例如:

^(?=[^a-z]*[a-z])(?=[^A-Z]*[A-Z])(?=[^0-9]*[0-9])(?=[^!@#$%^&*]*[!@#$%^&*])(?=[!@#$%^&*A-Za-z0-9]{8,}$)

正则表达式演示

您更新的代码可能如下所示:

 <input type="password" name="password_admin1_create" oninput="validate_password()"><br><br> <script> function validatePassword(password) { return /^(?=.*[az])(?=.*[AZ])(?=.*[0-9])(?=.*[!@#$%^&*])(?=.{8,})/.test(password); } var password = document.getElementsByName("password_admin1_create")[0]; function validate_password() { if (validatePassword(password.value)) { document.getElementById("password_result_invalid").style.visibility = "hidden"; document.getElementById("password_result_invalid").style.height = "0"; } else { document.getElementById("password_result_invalid").style.visibility = "visible"; document.getElementById("password_result_invalid").style.height = "initial"; } } </script> <div id="password_result_invalid" class="error_verify"> <p style="color:red">Invalid password format.</p> </div> <p>Please confirm the password:</p> <input type="password" name="password_admin1_create_confirm" oninput="return validate_password_confirm()"><br><br> <script> var password_confirm = document.getElementsByName("password_admin1_create_confirm")[0]; var password = document.getElementsByName("password_admin1_create")[0]; function validate_password_confirm() { if (password.value === password_confirm.value) { document.getElementById("password_confirmation_invalid").style.visibility = "hidden"; document.getElementById("password_confirmation_invalid").style.height = "0"; } else { document.getElementById("password_confirmation_invalid").style.visibility = "visible"; document.getElementById("password_confirmation_invalid").style.height = "initial"; } } </script> <div id="password_confirmation_invalid" class="error_verify"> <p style="color:red">Passwords do not match.</p> </div> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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