简体   繁体   中英

How could I limit the password to be a certain number of characters?

I need to limit the password characters to be 10 only as an example, not less not more..

There's only "maxlength" in HTML attributes, but there's no such "length" or "minlenght" to be used!

I have this code:

<input type="password" name="password" maxlength="9" pattern="\d+" value="<?php echo htmlentities($password); ?>" />

How could I limit the password to be a certain number of characters?

You could use JavaScript to do it. First attach the onblur event:

<input ... onblur="verifyMinLength(this, 10)"... />

and then in JavaScript:

function verifyMinLength(o, len) {
    if (o.value.length < len) {
        alert('The password must be 10 characters in length.');
        o.focus();
    }
}

of course this could be fancier. You could leverage a label that's placed next to the input control instead of the alert . You could also use CSS to change the border of the input control so the user gets some more feedback. But that's all up to you.

为什么不使用strlen?

if(strlen($password) < 10)

You need to validate the password after it is entered:

if (strlen($password) != 10)
{
  echo 'password must be 10 characters';
}

You can use HTML5. For me it's a good solution.

<form action="#" method="POST" id="form">
    <input pattern=".{10}" title="10 characters" placeholder="10 characters" name="password" type="password" />
    <input type="submit" value="Test" />
</form>

See in action: http://jsfiddle.net/a4B7z/ .

Not supported in Internet Explorer 9 and earlier versions, or in Safari.

Well I see you already have a lot of good answers here. Using a validation pattern like freejosh posted is the way I would do it. It seems to me to be the simplest and cleanest approach.

BUT.....

I have to agree with sammitch on this one. I would never limit a passwords length for the reasons he already stated. Having a minimum length can be a good thing since it forces the password to have a certain number of characters therefore (hopefully) increasing its security, but I would never give a limit for maximum length

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