Open In App

How to Validate Password using Regular Expressions in PHP ?

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 –




<?php
  
$password = "GeeksforGeeks@123";
  
$pattern = '/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,}$/';
  
if (preg_match($pattern, $password)) {
    echo "Valid Password";
} else {
    echo "Invalid Password";
}
  
?>

Output

Valid Password

In the above example –

Approach 2: Enhanced Password Strength

In this case, we will check the password contains –




<?php
  
$password = "GeeksforGeeks@123";
  
$pattern = '/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[\W_]).{8,}$/';
  
if (preg_match($pattern, $password)) {
    echo "Valid Password";
} else {
    echo "Invalid Password";
}
  
?>

Output
Valid Password

In above example, (?=.*[\W_]) defines at least one special character.


Article Tags :