Phone Number Validation

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
pennythetuff
Forum Newbie
Posts: 22
Joined: Sun Feb 19, 2006 6:05 pm
Location: Kokomo, Indiana

Phone Number Validation

Post 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.
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

\d{3}-\d{3}-\d{4}
pennythetuff
Forum Newbie
Posts: 22
Joined: Sun Feb 19, 2006 6:05 pm
Location: Kokomo, Indiana

Post 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?
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post 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.
pennythetuff
Forum Newbie
Posts: 22
Joined: Sun Feb 19, 2006 6:05 pm
Location: Kokomo, Indiana

Post by pennythetuff »

Worked! I don't know where the world would be without you Feyd. Thanks a million!
Post Reply