php validate phone number
Php validate phone number
libphonenumber for PHP
A PHP library for parsing, formatting, storing and validating international phone numbers. This library is based on Google’s libphonenumber.
PHP versions 5.3 up to PHP 8.0 are currently supported.
The PECL mbstring extension is required.
It is recommended to use composer to install the library.
You can also use any other PSR-4 compliant autoloader.
If you do not use composer, ensure that you also load any dependencies that this project has, such as giggsey/locale.
An online demo is available, and the source can be found at giggsey/libphonenumber-example.
Highlights of functionality
This library will try to follow the same version numbers as Google. There could be additional releases where needed to fix critical issues that can not wait until the next release from Google.
This does mean that this project may not follow Semantic Versioning, but instead Google’s version policy. As a result, jumps in major versions may not actually contain any backwards incompatible changes. Please read the release notes for such releases.
Google try to release their versions according to Semantic Versioning, as laid out of in their Versioning Guide.
Let’s say you have a string representing a phone number from Switzerland. This is how you parse/normalize it into a PhoneNumber object:
At this point, swissNumberProto contains:
Now let us validate whether the number is valid:
There are a few formats supported by the formatting method, as illustrated below:
You could also choose to format the number in the way it is dialled from another country:
Mapping Phone Numbers to carrier
Mapping Phone Numbers to TimeZones
Problems with Invalid Numbers?
This library uses phone number metadata from Google’s libphonenumber. If this library is working as intended, it should provide the same result as the Java version of Google’s project.
If you believe that a phone number is returning an incorrect result, first test it with libphonenumber via their Online Demo. If that returns the same result as this project, and you feel it is in error, raise it as an Issue with the libphonenumber project.
If Google’s Online Demo gives a different result to the libphonenumber-for-php demo, then please raise an Issue here.
Generating the data is not normally needed, as this repository will generally always have the up to data metadata.
If you do need to generate the data, the commands are provided by Phing. Ensure you have all the dev composer dependencies installed, then run
This compile process clones the libphonenumber project at the version specified in METADATA-VERSION.txt.
This project uses PHPUnit Bridge to maintain compatibility for the supported PHP versions.
Integration with frameworks
Other packages exist that integrate libphonenumber-for-php into frameworks.
Framework | Packages |
---|---|
Symfony | PhoneNumberBundle |
Laravel | Laravel Phone |
Yii2 | PhoneInput |
Kohana | PhoneNumber |
TYPO3 | TYPO3 Phone Extension |
These packages are supplied by third parties, and their quality can not be guaranteed.
About
PHP version of Google’s phone number handling library
regex phone number validation with PHP
This is another question about a previous question I had asked yesterday. I want user to be allowed to type US phone numbers in the following formats.
and have it only check the database for numbers 8005551212
may work but I’m not certain how to implement it into the code from the link I provided
I’m new to php and know nothing about regex. Any help is appreciated.
5 Answers 5
This function validate a phone number, return true if it validate and false if invalid. This function very simple i was wrote to.
if javascript is ok can go with
call this function onsubmit of form or onblur of textbox
If you have doubt about your regex you can validate it at http://www.regular-expressions.info/javascriptexample.html
You can use this pattern
Re: Rohan Kumar’s solution
It does address the issue of fake phone numbers such as 800-123-2222. Real phone numbers have a first digit of at least «2». While the other solutions do the format correctly, they don’t address the issue of people putting in phone numbers like 800-000-1234, which would be correct in the other solutions provided.
Not the answer you’re looking for? Browse other questions tagged php regex or ask your own question.
Linked
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.9.17.40238
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
Validate Phone Number and Zip Code PHP
I am trying to validate a phone number and require it to have 10 digits only no spaces or special characters allowed (example: 0123456789) and the same goes with zip code except 5 digits only (example: 01234).
This is what I have for the phone number field so far.
The next if statement should retrieve an error similar to «Please enter a valid phone number. Example: «0123456789».
5 Answers 5
If you don’t want to use regular expressions, take a look at ctype_digit
I can’t testify to whether this will be faster or slower than regular expressions, but I would reckon it’s probably moot. It’s more or less what makes the most sense to you.
You can try regex here:
Something a little like that will ensure only numerical characters and 10 of them. Just change the 10 to 5 for zip code.
Keep in mind that this will not allow foreign zip codes (which may be of different lengths or include letters)
Just some other suggestions too (to prevent unnecessary error messages)
You may want to process your user input such that 123-456-7890 becomes 1234567890 by doing something like
Maybe do a trim($input) to strip leading/trailing whitespace
Well, this an old post but I will throw in some comments here anyway.
Consider the following instead of putting the on the user:
Phone No Validation
International Phone Number Validation in PHP
International Phone Number Validation in PHP
In this tutorial you will learn about validation of International phone numbers using PHP programming. When phone numbers are obtained from users using form fields, its a good practice to validate the phone number value using PHP code. The following example explains how it can be done for International Phone Numbers.
International Phone Number Validation
For the above input, the error message generated is as shown below:
Sample PHP Code:
//Check whether the submission is made
if(!isset($_POST[«hidSubmit»]))<
//Declarate the necessary variables
$intisd=»»;
$intccode=»»;
$intphone=»»;
DisplayForm();
>
else<
//Assign the entered values to variables for validation
$intisd=$_POST[«txtisdcode»];
$intccode=$_POST[«txtcitycode»];
$intphone=$_POST[«txtphone»];
//The entered value is checked for proper format
if(substr_count($intisd,»+»)>0) <
if(strpos($intisd,»+»)==0)
$intisd=substr($intisd,1,strlen($intisd));
>
$result=ereg(«^7+$»,$intisd,$trashed);
$result=ereg(«^6+$»,$intisd,$trashed);
if(!($result))
$result=ereg(«^3+$»,$intccode,$trashed);
if(!($result))
$result=ereg(«^8+$»,$intphone,$trashed);
if(!($result))
DisplayForm();
>
Formatting Phone Numbers in PHP
I am working on an SMS app and need to be able to convert the sender’s phone number from +11234567890 to 123-456-7890 so it can be compared to records in a MySQL database.
The numbers are stored in the latter format for use elsewhere on the site and I would rather not change that format as it would require modifying a lot of code.
How would I go about this with PHP?
21 Answers 21
This is a US phone formatter that works on more versions of numbers than any of the current answers.
And here is a breakdown of the regex:
Updated: March 11, 2015 to use <0,7>instead of
This function will format international (10+ digit), non-international (10 digit) or old school (7 digit) phone numbers. Any numbers other than 10+, 10 or 7 digits will remain unformatted.
Assuming that your phone numbers always have this exact format, you can use this snippet:
Phone numbers are hard. For a more robust, international solution, I would recommend this well-maintained PHP port of Google’s libphonenumber library.
Using it like this,
you will get the following output:
I’d recommend using the E164 format for duplicate checks. You could also check whether the number is a actually mobile number or not (using PhoneNumberUtil::getNumberType() ), or whether it’s even a US number (using PhoneNumberUtil::getRegionCodeForNumber() ).
As a bonus, the library can handle pretty much any input. If you, for instance, choose to run 1-800-JETBLUE through the code above, you will get
It works just as nicely for countries other than the US. Just use another ISO country code in the parse() argument.
It’s faster than RegEx.
Here’s my USA-only solution, with the area code as an optional component, required delimiter for the extension, and regex comments:
And here’s the script to test it:
The sscanf function takes as a second parameter a format string telling it how to interpret the characters from the first string. In this case, it means 2 characters ( %2c ), 3 characters, 3 characters, 4 characters.
I have used a similar function to format Australian phone numbers.
Note that from the perspective of storing the phone number:
Here’s a simple function for formatting phone numbers with 7 to 10 digits in a more European (or Swedish?) manner:
It is based on Google’s library for parsing, formatting, and validating international phone numbers: https://github.com/google/libphonenumber
I see this being possible using either some regex, or a few substr calls (assuming the input is always of that format, and doesn’t change length etc.)
Try something like:
I think I fixed it. Working for current input files and have following 2 functions to get this done!
function format_phone_number:
function validate_phone_number:
Notice I have this in a class lib, so thus the «self::validate_phone_number» call from the first function/method.
Notice line # 32 of the «validate_phone_number» function where I added the:
to get me the false return needed if not valid phone number.
Still need to test this against more data, but working on current data, with current format and I’m using style ‘8’ for this particular data batch.
Also I commented out the «extension» logic as I was constantly getting errors from it, seeing I do not have any of that info in my data.
this takes 7, 10 and 11 digit, removes additional characters and adds dashes by going right to left through the string. change the dash to a space or dot.
I know the OP is requesting a 123-456-7890 format, but, based on John Dul’s answer, I modified it to return the phone number in parentheses format, e.g. (123) 456-7890. This one only handles 7 and 10 digit numbers.
United Kingdom Phone Formats
For the application I developed, I found that people entered their phone number ‘correctly’ from a human readable form, but inserted varous random characters such as ‘-‘ ‘/’ ‘+44’ etc. The problem was that the cloud app that it needed to talk to was quite specific about the format. Rather than use a regular expression (can be frustrating for the user) I created an object class which processes the entered number into the correct format before being processed by the persistence module.
+441234567890 produces (01234) 567 890
02012345678 produces (020) 1234 5678
1923123456 produces (01923) 123 456
01923123456 produces (01923) 123 456
01923hello this is text123456 produces (01923) 123 456
I’m sure that there are more efficient solutions, but this one has proved extremely reliable. More formats can easily be accomodated by adding to the teleNum function at the end.
The procedure is invoked from the calling script thus