I've got this script to validate phone numbers. I want to allow numbers 0-9 and the characters -,(,) and + the following seems to only work if the input is all numbers and spaces. Suggestions?

if(!ereg("^[0-9\-\(\)\ \+]+$", $phoneNumber)||empty($phoneNumber)){
print'Please enter a valid phone number' ;					$error++;
}

Recommended Answers

All 6 Replies

From comment posted in POSIX regular expressions section of PHP Manual:

I was having a ton of issues with other people's phone number validation expressions, so I made my own. It works with most US phone numbers, including those with extentions. Format matches any of the following formats:

5551234567
555 1234567
555 123 4567
555 123-4567
555-1234567
555-123-4567
555123-4567
(555)1234567
(555)123 4567
(555)123-4567
(555) 1234567
(555) 123-4567
(555) 123 4567

And any of the following extentions can be added with or without a space between them and the number:
x123
x.123
x. 123
x 123
ext.123
ext. 123
ext 123
ext123

Extentions support between 1 and 5 digits.

Here is the expression:

$regex = '^[(]?[2-9]{1}[0-9]{2}[) -]{0,2}' . '[0-9]{3}[- ]?' . '[0-9]{4}[ ]?' . '((x|ext)[.]?[ ]?[0-9]{1,5})?$';

Member Avatar for iamthwee

>I want to allow numbers 0-9 and the characters -,(,) and +

If this is all you want you don't even need regular expressions.

Ok... how would you do it?

try dis one...
<?php

if (!preg_match('/[^((0-9)|\-|\(|\)|\+)]+/', $number) && !empty($number)) {
print "Valid phone number!!!\n";
}
else {
print "Please enter valid phone number!!!";
}
?>

if (!preg_match('/[^((0-9)|\-|\(|\)|\+)]+((x|ext)[.]?[ ]?[0-9]{1,5})?$/', $number) && !empty($number)) {
print "Valid phone number!!!\n";
}
else {
print "Please enter valid phone number!!!";
}

the last one for the extension checking......

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.