PHP Tutorials

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.

Example:

International Phone Number Validation

 
Enter your Phone Number Country Code
Area Code
Phone Number


For the above input, the error message generated is as shown below:

  • Error Enter valid ISD Code
  • Error Enter valid Area Code
  • Error Enter valid Phonenumber.
Use the sample code given below in your test page and try it yourself.

Sample PHP Code:

<?php
//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("^[0-9]+$",$intisd,$trashed);
$result=ereg("^[0-9]+$",$intisd,$trashed);
if(!($result)){echo "Enter Valid ISDCODE";}
$result=ereg("^[0-9]+$",$intccode,$trashed);
if(!($result)){echo "Enter Valid CITY CODE";}
$result=ereg("^[0-9]+$",$intphone,$trashed);
if(!($result)){echo "Enter Valid Phone Number";}
DisplayForm();
}

//User-defined Function to display the form in case of Error
function DisplayForm(){
global $intisd,$intccode,$intphone;

?>

HTML code for the form follows..

Cut 'n' Paste Code for the above Example

HTML CODE

Refer: Explanation of Code

Please like, +1, link to and share this SmartWebby resource if you found it helpful. Thanks!