Open In App

How to set Minimum Length of Password in HTML ?

Setting the minimum length of a password facilitates notifying the user to insert the min. password length, without leaving the field vacant while submitting the form. This helps to authenticate the user and also ensures that users create sufficiently strong passwords that are harder to guess or crack. Setting a minimum length for passwords is a common practice to enhance security in web applications.

Using the pattern Attribute

One approach is to use the pattern attribute in conjunction with a regular expression to enforce a minimum password length. Here, the pattern=”.{8,}” attribute is applied to the password input field. This regular expression {8,} ensures that the password contains at least 8 characters.

Example:






<!DOCTYPE html>
<html lang="en">
  
<head>
    <title>
        Set Minimum Length of Password
        with pattern Attribute
    </title>
  
    <style>
        body {
            text-align: center;
        }
    </style>
</head>
  
<body>
    <form>
        <label for="password">
            Password (at least 8 characters):
        </label>
  
        <input type="password"
               id="password"
               name="password" 
               pattern=".{8,}" required>
  
        <button type="submit">Submit</button>
    </form>
</body>
  
</html>

Output:

Using the minlength Attribute

The minlength attribute can be used to specify the minimum length directly without the need for a regular expression. Here, the minlength=”8″ attribute is used to set the minimum length of the password to 8 characters.

Example:




<!DOCTYPE html>
<html lang="en">
  
<head>
    <title>
        Set Minimum Length of Password
        with minlength Attribute
    </title>
  
    <style>
        body {
            text-align: center;
        }
    </style>
</head>
  
<body>
    <form>
        <label for="password">
            Password (at least 8 characters):
        </label>
  
        <input type="password" 
               id="password" 
               name="password"
               minlength="8" required>
  
        <button type="submit">Submit</button>
    </form>
</body>
  
</html>

Output:


Article Tags :