How to do password validation in Python using regex
Recently, more users are susceptible to data breaches, and one of the most common causes of these data breaches is having a weak password, which can be easily brute-forced by hackers. One of the ways to protect users from losing their data to this is to make sure that their accounts are protected by strong passwords. But how can we verify if the password the users are inputting is secure?
We can use regex.
What is regex?
Regular expressions (regex) are a sequence of characters that define a pattern. It is an indispensable tool used in computer programming and text processing to match and manipulate text based on a specific pattern. They are supported by many popular languages such as Python, Javascript, Perl, and so on. For our example, we'll focus on Python.
Using regex for password validation
Let's assume that we are developing a sign-up system for an e-commerce website and the user password needs to meet the following criteria:
The password must be at least eight characters long.
The password must contain at least one uppercase letter.
The password must contain at least one lowercase letter.
The password must contain at least one digit.
Code
Let's see how we can use regex to validate passwords according to the given requirements in the following code snippet:
import redef validate_password(password):# define our regex pattern for validationpattern = r"^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}$"# We use the re.match function to test the password against the patternmatch = re.match(pattern, password)# return True if the password matches the pattern, False otherwisereturn bool(match)password1 = "StrongP@ssword123"password2 = "weakpassword"print(validate_password(password1))print(validate_password(password2))
In Python, we can use the re library for all regex operations.
Line 1: We import the
remodule.Line 2: We define a function named
validate_passwordthat takes a string.Line 5: We define a pattern we can use for password validation.
Line 8: We use the
re.match()function to test the string against the pattern.Line 11: We return a boolean value that will be
Trueif the string matches the pattern. Otherwise, it will beFalse.Lines 13–16: We simply test our program.
Free Resources