How to validate phone number using php
-
1Please define what makes a phone number valid?Gordon– Gordon2010-06-22 06:58:00 +00:00Commented Jun 22, 2010 at 6:58
-
2your missing the other planets..Ben Rowe– Ben Rowe2010-06-22 06:58:19 +00:00Commented Jun 22, 2010 at 6:58
-
In my country they don't. Plus there might be an international prefix. Or an extension. Depending on the country, digit groups get distanced with spaces, dots or dashes. Ergo: Validation is culture dependend and not quite as simple as you think.Christian Studer– Christian Studer2010-06-22 06:58:43 +00:00Commented Jun 22, 2010 at 6:58
-
4is this an Australian phone number, a UK number, an international number, etc, etc? Validating phone numbers from around the world can open up more worms than email validation - and I don't think I've ever seen that done 100% infallible.HorusKol– HorusKol2010-06-22 07:15:12 +00:00Commented Jun 22, 2010 at 7:15
-
2Best solution is to use libphonenumber which is a port of Google's libphonenumber to PHP github.com/giggsey/libphonenumber-for-phpjbrahy– jbrahy2019-08-22 19:35:23 +00:00Commented Aug 22, 2019 at 19:35
3 Answers
Here's how I find valid 10-digit US phone numbers. At this point I'm assuming the user wants my content so the numbers themselves are trusted. I'm using in an app that ultimately sends an SMS message so I just want the raw numbers no matter what. Formatting can always be added later
//eliminate every char except 0-9
$justNums = preg_replace("/[^0-9]/", '', $string);
//eliminate leading 1 if its there
if (strlen($justNums) == 11) $justNums = preg_replace("/^1/", '',$justNums);
//if we have 10 digits left, it's probably valid.
if (strlen($justNums) == 10) $isPhoneNum = true;
Edit: I ended up having to port this to Java, if anyone's interested. It runs on every keystroke so I tried to keep it fairly light:
boolean isPhoneNum = false;
if (str.length() >= 10 && str.length() <= 14 ) {
//14: (###) ###-####
//eliminate every char except 0-9
str = str.replaceAll("[^0-9]", "");
//remove leading 1 if it's there
if (str.length() == 11) str = str.replaceAll("^1", "");
isPhoneNum = str.length() == 10;
}
Log.d("ISPHONENUM", String.valueOf(isPhoneNum));
3 Comments
Since phone numbers must conform to a pattern, you can use regular expressions to match the entered phone number against the pattern you define in regexp.
php has both ereg and preg_match() functions. I'd suggest using preg_match() as there's more documentation for this style of regex.
An example
$phone = '000-0000-0000';
if(preg_match("/^[0-9]{3}-[0-9]{4}-[0-9]{4}$/", $phone)) {
// $phone is valid
}
8 Comments
I depends heavily on which number formats you aim to support, and how strict you want to enforce number grouping, use of whitespace and other separators etc....
Take a look at this similar question to get some ideas.
Then there is E.164 which is a numbering standard recommendation from ITU-T