How to Validate Password using Regular Expressions in PHP ?
Last Updated :
17 Jan, 2024
Password validation is a crucial part of web application security. Regular expressions provide a powerful tool to define complex patterns. This article will guide you through various approaches to validate passwords using regular expressions in PHP.
Approach 1: Basic Password Validation
In this case, we will use basic password validation using a regular expression.
The basic password contains –
- password minimum length should be 8.
- at least one uppercase letter,
- at least one lowercase letter,
- and one digit.
PHP
<?php
$password = "GeeksforGeeks@123" ;
$pattern = '/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,}$/' ;
if (preg_match( $pattern , $password )) {
echo "Valid Password" ;
} else {
echo "Invalid Password" ;
}
?>
|
In the above example –
- (?=.*[a-z]): At least one lowercase letter.
- (?=.*[A-Z]): At least one uppercase letter.
- (?=.*\d): At least one digit.
- .{8,}: Minimum length of 8 characters.
Approach 2: Enhanced Password Strength
In this case, we will check the password contains –
- minimum length should be 8.
- at least one uppercase letter.
- at least one lowercase letter.
- at least one digits, and
- at least one special character.
PHP
<?php
$password = "GeeksforGeeks@123" ;
$pattern = '/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[\W_]).{8,}$/' ;
if (preg_match( $pattern , $password )) {
echo "Valid Password" ;
} else {
echo "Invalid Password" ;
}
?>
|
In above example, (?=.*[\W_]) defines at least one special character.
Share your thoughts in the comments
Please Login to comment...