Validating Telephone Numbers With PHP

Written by Mark Sanborn: May 30, 2008

There are many different ways a user might input a phone number. Sometimes they may choose to input it as, (555) 555-5555. Other times they will use 555-555-5555. As a developer we never really know how they might input the number. Often times we can give our users an example and they will still enter the wrong format. I have created a script that will strip out all characters in a string except numerical digits. This not only creates a standardized string that can be later used in a comparison or stored in a database, but also ensures that the data that is received on the server end contains only the expected data. This is important because most website attacks are caused by accepting user input blindly.

Client vs Server Validation

There are two ways of validating user input, server side and client. On the client side we could have javascript that checks the form for certain validation requirements when the user clicks the submit button. This is a great way to validate the input since the user will be notified before submitting the data if it is valid or not.

The problem with validating user input on the client side is that there is no security. The user could simply turn off all javascript or send the data through curl or some other method that bypasses the validation script. For security purposes it is imperative that we validate all user input on the server side. The problem with the server side validation is that the people that make an honest mistake must suffer a page refresh.

As an answer to this problem most sites will use both forms of validation. That way if the user makes an honest mistake a javascript popup can alert you before you submit; however, if you have javascript turned off the data will be submitted but the server will validate and reject the error.

Validating Telephone Numbers with PHP (Server Side)

Here is the function that I came up with for validating telephone numbers with PHP:

function validatePhone($string) {
    $numbersOnly = ereg_replace("[^0-9]", "", $string);
    $numberOfDigits = strlen($numbersOnly);
    if ($numberOfDigits == 7 or $numberOfDigits == 10) {
        echo $numbersOnly;
    } else {
        echo 'Invalid Phone Number';
    }
}

Validating Telephone Numbers with JavaScript (Client Side)

To validate via javascript you would need something along these lines:

var stripped = strng.replace(/[\(\)\.\-\ ]/g, '');
if (isNaN(parseInt(stripped))) {
   error = "Invalid Phone Number";
}

Need to print shipping labels on your site?

Checkout my product RocketShipIt for simple easy-to-use developer tools for UPS™ FedEx™ USPS™ and more.

Share: