Saturday, June 14, 2008

Validate a Phone Number with PHP

How to Validate a Phone Number with PHP

I expect You wanna match 555-666-0606? (Angelina Jolies number ;-)

This will match the number from start to end:

^[0-9]{3}-[0-9]{3}-[0-9]{5}$

^ means the start of the string
$ means the end of the string
[0-9] means any number from 0 to 9
{3} means _exactly_ 3 occurences, no more no less (can also be {2,4} if
You world allow from 2 to 4 occurences or {2,} if You want at least 2
digits)

So this line says _start_ with 3 digits followed by a - then 3 digits,
then another - and end with 4 digits

Example:
<?php
$number 
"555-666-0606";

if(
ereg("^[0-9]{3}-[0-9]{3}-[0-9]{4}$"$number)) {
echo 
"valid phonenumber";
}
else {
echo 
"invalid phonenumber";
}

?>

No comments:

Post a Comment

Got a Suggestion please let us know