简体   繁体   中英

PHP Regex for password validation failing in different environment

We're using the below function to validate passwords as per customer requirements. This works in our dev environment as well as the customers staging environment but when pushing to production passwords fail randomly. Staging and production is suppose to be identical and making it very difficult to figure out why it's not working as we do not have access to the production environment.

The password needs to validate the following:

  1. At least 1 upper-case and 1 lower-case alpha character
  2. At least 1 numeric digit (0-9)
  3. At least 10 characters long
  4. Contains 1 of the following characters - !@#$%^&*() ( Shift + any numeric digit on a Standard US Keyboard)
  5. Should be in no particular order as long as the above validates

The code works in our dev environment so it may work for you as well. What we need is to look at why it may fail and

<?php
function isStrongPassword($pass, $char = 10) {
     $bits = ['A-Z', 'a-z', '0-9',preg_quote('#$%^&*()','/')];
         if (is_numeric($char) && strlen($pass) >= $char) {
              foreach ($bits AS $bit) {
                  if (preg_match('@[' . $bit . ']@', $pass) == false) {
                      return false;
                  }
              }
              return true;
          }
          return false;
       }
?>

Translating my comment into an answer.

It seems all the code in answer can be translated into a single regex using lookaheads as this:

/^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[!@#$%^&*()]).{10,}$/

Each of 4 lookaheads (?=...) ensures presence of an uppercase letter, lowercase letter, digit and a special character. .{10,} ensures minimum length is 10 for input.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM