如何设置密码的最小长度

How to set minimum length of password

我目前正在处理 html 表格。如何将密码的最小长度设置为 8,以便拒绝用户输入的任何小于 8 的密码。如何操作?

代码如下:

<div id="login-form">
            <form method="post">
            <table align="center" width="30%" border="0">
            <tr>
            <td><input type="text" name="email" placeholder="Your Email" required /></td>
            </tr>
            <tr>
            <td><input type="password" name="pass" placeholder="Your Password" required /></td>
            </tr>
            <tr>
            <td><button type="submit" name="btn-login">Sign In</button></td>
            </tr>
            <tr>
            <td><a href="register.php">Sign Up Here</a></td>
            </tr>
            </table>
            </form>
        </div>

将您的按钮更改为:

<button name="btn-login">Sign In</button>

并添加此代码 JavaScript(使用 jquery):

$('button[name="btn-login"]').click(function() {
    if($('input[name="pass"]').val().length < 8) {
        alert('Minimum length = 8');
    } else {
        $('form').submit();
    }
});

不要忘记将此条件添加到您的 PHP 代码中。

如果您使用的是 HTML5,则可以使用 pattern 和输入标签所需的属性:

<input type="password" pattern=".{8,}"   required title="8 characters minimum">
<input type="password" pattern=".{8,12}" required title="8 to 12 characters">

还有一个minlength attribute for input tags but it does not work in some browsers:

<input type="password" minlength="8" required>

您可以使用模式属性:

<input pattern=".{8,}" type="password" name="pass" placeholder="Your Password" required />

遗憾的是,并非所有浏览器都支持最小长度属性。请check this out

因此,必须使用替代方法。

我选择使用正则表达式,如下所示;

<input type="password" name="pass" title="Password must be 8 characters including 1 uppercase letter, 1 lowercase letter and numeric characters" required pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}" >

您可以使用 minlengthmaxlength

As usual, you can use the minlength and maxlength attributes to establish minimum and maximum acceptable lengths for the password. This example expands on the previous one by specifying that the user's PIN must be at least four and no more than eight digits. The size attribute is used to ensure that the password entry control is eight characters wide.

Source

But it works on Chrome only at the moment.

或者,正如有人已经提到的,您可以使用 pattern

If your application has character set restrictions or any other requirement for the actual content of the entered password, you can use the pattern attribute to establish a regular expression to be used to automatically ensure that your passwords meet those requirements.

Source

<input type="Password" name="pd" placeholder="Password" pattern=".{8,16}" title="8 or more Character" size=30 pattern="[!@#$%^&*][a-z][A-Z][0-9]" required>

这段代码对我有用。试试这个