1

Possible Duplicate:
A comprehensive regex for phone number validation
PHP: Validation of US Phone numbers

I'm trying to validate a phone number using preg_match, but any time I type in the correct format of phone number (111) 111-1111, it returns the invalid character error instead of true. I don't think there's anything wrong with my regex (as far as I know), so I'm guessing there's something wrong with my logic

function validate_phone_number($phoneNumber, $requiredLength = 14)
{

       //Check to make sure the phone number format is valid 
    for ($i = 0; $i < strlen($_POST[$phoneNumber]); $i++){
            if(preg_match('/^\(\d{3}\) \d{3}-\d{4}\$/', $_POST[phoneNumber]{$i}))
            {
                return true;
            }
            else
            {
                return "<h3>" . "The phone number you entered contains invalid characters" . "</h3>";
            }

       //Check to make sure the number is the required length
            if (strlen($_POST[$phoneNumber]) > $requiredLength) {
                return "<h3>" . "The phone number you entered contains too many characters" . "</h3>";
            }
            else if (strlen($_POST[$phoneNumber]) < $requiredLength) {
                return "<h3>" . "The phone number you entered does not contain enough characters" . "</h3>";
            }
        }
        return true;
}

What I'm using to call the function

if (count($_POST) > 0) {
    $error = array();


   $phone = validate_phone_number('phoneNumber');
        if($phone !==true) {
            $error[] = $phone;

        }


        if (count($error) == 0) {

           //Phone number validates

        }

        else { 
          echo "<h2>Error Message:</h2>";

          foreach($error as $msg) {
            echo "<p>" . $msg . "</p>";
          }
        }
      }
Community
  • 1
  • 1
Brian Houlihan
  • 71
  • 1
  • 2
  • 8
  • a lot of phone numbers would not fit that format. –  Oct 28 '12 at 18:47
  • One thing I spotted which seems to be wrong: `validate_phone_number()` has a dependency to `$_POST` which it should not have. Pass everything that the function needs to word as parameters instead. This might be the error, you might want to replace it with the first function parameter already. – hakre Oct 28 '12 at 18:48
  • I assume you're a US-only web site? I mention this because this because the phone format you're using is wrong for most countries in the world. – Spudley Oct 28 '12 at 19:05
  • between taking mario's and hakre's advice, It worked! Thanks guys. I'd up-vote if my reputation was high enough. And I know that it's not a good thing to only use that format but this is just for practice purposes – Brian Houlihan Oct 28 '12 at 19:17
  • Brian - I gave them an up-vote on your behalf - Your get a up vote as well. Welcome to the board. – Ed Heal Oct 28 '12 at 19:30

2 Answers2

1

Two things wrong here:

for ($i = 0; $i < strlen($_POST[$phoneNumber]); $i++){
        if(preg_match('/^\(\d{3}\) \d{3}-\d{4}\$/', $_POST[phoneNumber]{$i}))

Firstly you used phoneNumber as bare constant. But in the rest of your code you used $phoneNumber as name reference. Change that. (Better yet, pass the $value to your function, not a reference key to $_POST).

Secondly, you seem to be iterating over it character-wise {$i}. But the regex is supposed to be applied to the whole string. Curb the for.

function validate_phone_number($phoneNumber, $requiredLength = 14)
{    
    //Check to make sure the phone number format is valid 
    if (preg_match('/^\(\d{3}\) \d{3}-\d{4}\$/', $_POST[$phoneNumber]))
    {

The length check is entirely redundant, as the regex will already assert your fixed format.

mario
  • 144,265
  • 20
  • 237
  • 291
1

The two main things I see:

You have a problem with the regular expression:

'/^\(\d{3}\) \d{3}-\d{4}\$/'
                        ^- wrong. leave it out:

'/^\(\d{3}\) \d{3}-\d{4}$/'

As you test first for the regular expression, it will only match if the string is exactly 14 characters. Because of that, the check for the string length afterwards is not necessary.

You should also consider to make use of the filter_var function, an example:

$options['options'] = array('regexp' => '/^\(\d{3}\) \d{3}-\d{4}$/');
$valid = filter_var($number, FILTER_VALIDATE_REGEXP, $options);

It also has a filter_input sister function that is able to operate on $_POST input. Might be handy:

$options['options'] = array('regexp' => '/^\(\d{3}\) \d{3}-\d{4}$/');
$valid = filter_input(
    INPUT_POST, 'phoneNumber', FILTER_VALIDATE_REGEXP, $options
);
hakre
  • 193,403
  • 52
  • 435
  • 836