Page 1 of 1

Phone Number Validation

Posted: Sun Feb 19, 2006 10:59 pm
by pennythetuff
Hey everybody,
I'm trying to validate phone numbers (include area codes, and later country codes), and I'm wanting to accept:

555-555-5555

I've been going over the regex tutorials, but I'm having a hard time figuring this out. Thanks to anyone that can help.

Posted: Sun Feb 19, 2006 11:01 pm
by feyd
\d{3}-\d{3}-\d{4}

Posted: Sun Feb 19, 2006 11:09 pm
by pennythetuff
Here's how I'm implementing it:

Code: Select all

if(!preg_match("/\d{3}-\d{3}-\d{4}/", $_POST['phone_number'])) {
  	$error_message[$error_counter++] = "Please enter a valid phone number.";
}
I have a problem though. When I put 5555-555-5555 through it won't error out. If I put 555-555-55555 it won't error out. If I put 555-5555-5555 it WILL error out. Am I implementing this wrong?

Posted: Sun Feb 19, 2006 11:12 pm
by feyd
no, you didn't implement it wrong; it's looking for it anywhere in the string supplied.

Code: Select all

if(!preg_match("/^\d{3}-\d{3}-\d{4}$/s", $_POST['phone_number'])) {
      $error_message[$error_counter++] = "Please enter a valid phone number.";
}
will force full string matching.

Posted: Sun Feb 19, 2006 11:14 pm
by pennythetuff
Worked! I don't know where the world would be without you Feyd. Thanks a million!