2

Possible Duplicate:
How to validate phone number using PHP?

can anyone please help me know how to validate if the field value entered is a phone number using php... I have used a variable $phone , datatype =varchar 10 in sql db Now i want to validate that users enter only numbers in that field..

Community
  • 1
  • 1
mo0206
  • 791
  • 5
  • 20
  • 36

3 Answers3

0

use preg_match

if(preg_match('/^(NA|[0-9+-]+)$/',$str)) {
        *code here*
} else {
        "code here"
}
MANG KANOR
  • 44
  • 2
  • 9
0

One way to do this is with regular expressions. When validating phone numbers, it's easier on users if you accept accompanying characters, and filter them out yourself (-+()).

http://www.php.net/manual/en/function.preg-replace.php

$phone = preg_replace ( '/[+\\.\\(\\) ]/' , '' , $phone);

Once you've done that, checking for a match of 10 digits (assuming U.S. numbers with area code) can be done like so:

if(preg_match ( '/^\\d{10}$/', $phone) ) {
    // Good match
}

http://www.php.net/manual/en/function.preg-match.php

alttag
  • 1,163
  • 2
  • 11
  • 29
-1

Does is_numeric solve your problem?

Edit: I wasn't aiming to solve OPs problem, merely hoping to give him/her pointers. However, reading the question closer makes me think that OP isn't being conscious of internationalisation issues. Her field is 10 characters long, so a number like +447970122467 (a valid British mobile number) would cause a failure. I'm going to assume they are in North America, and as such can assume that all numbers are in accordance with the North American Numbering Plan. The description of this, in words, is taken from that page:

Component Name Number ranges Notes

+1 ITU country calling code "1" is also the usual trunk code for accessing long-distance service between NANP numbers. In an intra-NANP context, numbers are usually written without the leading "+"

NPA Numbering Plan Area Code Allowed ranges: [2–9] for the first digit, and [0–9] for both the second and third digits. Covers Canada, the United States, parts of the Caribbean Sea, and some Atlantic and Pacific islands. The area code is often enclosed in parentheses.

NXX Central Office (exchange) code Allowed ranges: [2–9] for the first digit, and [0–9] for both the second and third digits. Often considered part of a subscriber number. The three-digit Central Office codes are assigned to a specific CO serving its customers, but may be physically dispersed by redirection, or forwarding to mobile operators and other services.

xxxx Subscriber Number [0–9] for each of the four digits. This unique four-digit number is the subscriber number or station code.`

That ought to be enough to get OP started on solving their problem. Sorry for being curt in my initial response.

Community
  • 1
  • 1
hd1
  • 33,938
  • 5
  • 80
  • 91