deCODE - Our Newsletter for Jan 2022 is available for Download. 🗞   🥳
  Signup/Sign In

How to use pattern to validate Password?

The passwords are used to secure web access from any invalid users. But with the advancement of technology, simple passwords can be easily cracked by hackers and can access your content. So nowadays developers have designed some patterns for passwords that cannot be easily cracked by hackers. When the user enters the passwords this pattern is validated. In this tutorial, we will learn to validate passwords using the HTML pattern attribute.

HTML pattern attribute

The password field is created using <input> tag with type="password". To add some definite pattern to the password use pattern attribute. The pattern contains some regular expressions that must be validated in order to successfully create a password.

Let's learn by examples.

Example: Add a pattern to the password

Password Validation: The below element pattern(regular expression) will be applied to password field.

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

(?=.*[a-z]) - At least one lowercase letter(a - z).

(?=.*[A-Z]) - At least one uppercase letter(A - Z).

(?=.*[0-9]) - At least one numeric value(0-9).

(?=.*[!@#$%^&*_=+-]) - At least one special symbol(!@#$%^&*=+-_)

{8,16} -> The total length should be greater than or equal to 8 and less or equal to 16.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>HTML</title>
</head>
<body>
    <h2>Password Input validation</h2>
    <label for="pswd">Enter password:</label>
	<input type="password" name="pswd" id="pswd" pattern="^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#$%^&*_=+-]).{8,16}$">
	<input type="submit">
</body>
</html>

Output

password input field

Example: Validate password using pattern and CSS

Here in this program, we have used CSS to change the border color of the input field when we enter the valid password and user name. The red color border changes to the green color border after a valid input.

Conclusion

The password can be validated using the pattern attribute within the input password field. The pattern attribute requires a regular expression to validate a password.