Password Validation in Python



It is a general requirement to have a reasonably complex password. In this article we will see how to validate if a given password meats certain level of complexity. For that will use the regular expression module known as re.

Example -1

First we create a regular expression which can satisfy the conditions required to call it a valid password. Then we e match the given password with the required condition using the search function of re. In the below example the complexity requirement is we need at least one capital letter, one number and one special character. We also need the length of the password to be between 8 and 18.

Example

 Live Demo

import re

pswd = 'XdsE83&!'
reg = "^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*#?&])[A-Za-z\d@$!#%*?&]{8,18}$"

# compiling regex
match_re = re.compile(reg)

# searching regex
res = re.search(match_re, pswd)

# validating conditions
if res:
   print("Valid Password")
else:
   print("Invalid Password")

Output

Running the above code gives us the following result −

Valid Password

Example -2

In this example we e use a password which does not meet all the required conditions. For example, no numbers in the password. In that case the program indicates it it as invalid password.

Example

 Live Demo

import re

pswd = 'XdsEfg&!'
reg = "^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*#?& ])[A-Za-z\d@$!#%*?&]{8,18}$"

# compiling regex
match_re = re.compile(reg)

# searching regex
res = re.search(match_re, pswd)

# validating conditions
if res:
   print("Valid Password")
else:
   print("Invalid Password")

Output

Running the above code gives us the following result −

Invalid Password
Updated on: 2020-07-10T11:22:16+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements