In this post, we are going to learn how to validate a password in Python. Programmers need to validate the password is valid or not. When a user creates a new account and enters a password or a user try to log in, it comes into the picture. The string that the user enters, needs validation on certain parameters. So we will be setting some password criteria and then we will be validating the password string if it is a valid input or not.
Rules to set a Valid password are :
- It should be a minimum of 8 characters.
- The characters must be between a to z
- Minimum one character should be of Upper Case between A to Z
- Minimum one number between 0 to 9
- Minimum one At special character from [ _ or @ or $ or ! or # or % or & or * ].
To implement this program we will be using regular expression in Python. Let us begin:
1.Using Regular Expression To validate a Password
In this code example, as we had mentioned the password will be validated and if it fulfills all the above points it will be accepted as a valid password. So we are implementing all the above points by code one by one.
Program to Validate a Password in Python
# importing regular expression import re inputpassword = "Sa#c1hin%" validity = 0 while True: if (len(inputpassword)<8): validity = -1 break elif not re.search("[a-z]", inputpassword): validity = -1 break elif not re.search("[A-Z]", inputpassword): validity = -1 break elif not re.search("[0-9]", inputpassword): validity = -1 break elif not re.search("[@$!#%&]", inputpassword): validity = -1 break elif re.search("\s", inputpassword): validity = -1 break else: validity = 0 print("Password ia Valid") break if validity ==-1: print("Password is Invalid")
Password is Valid
2. Custom function To validate a Password
In this example, we wrote a custom logic to validate a password in Python
lowercase, uppercase, specialchar, number = 0, 0, 0, 0 inputpassword = "S*a#_c1hin%" if (len(inputpassword) >= 8): for i in inputpassword: # counting lowercase alphabets if (i.islower()): lowercase+=1 # counting uppercase alphabets if (i.isupper()): uppercase+=1 # counting digits if (i.isdigit()): number+=1 # counting the mentioned special characters if(i=='@'or i=='$' or i=='_' or i == '!' or i == '#' or i == '%' or i == '&' or i == '*' ): specialchar+=1 if (lowercase>=1 and uppercase>=1 and specialchar>=1 and number>=1 and lowercase+specialchar+uppercase+number==len(inputpassword)): print("Password is Valid") else: print("Password is Invalid")
Password is Valid
In this article, we learned the techniques about the verification of passwords that can help us to verify the password string which is entered by the user. This is one of the most important use cases where we need to verify passwords.
We hope you enjoyed this article!!