
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
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
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