-1

Possible Duplicate:
A comprehensive regex for phone number validation

please i created this function for mail and phone number validation, the mail own works, bt the phone own does nt work.

if(trim($_POST['email']) == '')  {
    $hasError = true;
} else if (!eregi("^[A-Z0-9._%-]+@[A-Z0-9._%-]+\.[A-Z]{2,4}$",     
         trim($_POST['email']))) {
    $hasError = true;
} else {
    $email = trim($_POST['email']);
}

if(trim($_POST['phonenumber']) == '')  {
    $hasError = true;
} else if (!eregi("/^\(?(\d{3})\)?[- ]?(\d{3})[- ]?(\d{4})$/$",      
          trim($_POST['phonenumber']))) {
    $hasError = true;
} else {
    $phonenumber= trim($_POST['phonenumber']);
}
Community
  • 1
  • 1
  • Is it the trailing `$/$'? Try changing it to just `$` and see if that works.... – andrewsi Jun 21 '12 at 16:44
  • `ereg` functions are deprecated. See [`preg`](http://il.php.net/manual/en/book.pcre.php). Also, please clearly define what a valid phone number is. – Madara's Ghost Jun 21 '12 at 16:45

2 Answers2

0

Firstly, you should be using preg_match instead of eregi.

Aside from that, people enter phone numbers in a variety of ways. The easiest way to handle them is to strip out anything that isn't a digit, and see if you have ten digits:

$number = preg_replace("/\D/","",$_POST['phonenumber']);
if( strlen($number) == 10) { /* ok */ }
else { /* error */ }
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
0

I think a better way to do it would be to strip all non-numeric characters from the input and check that the length is within a certain range. Especially if you're storing this data in a database so you don't end up storing unnecessary data.

You might want to leave the x character in if you want to allow extensions. Here's a function to remove all non-digit characters from a string (except x).

function removeNonNumeric($string) {
    return preg_replace('/[^\dx]/', '', $string)
}

When you need to output the result, you can format it however you want.

sachleen
  • 30,730
  • 8
  • 78
  • 73