Possible Duplicate:
A comprehensive regex for phone number validation
PHP: Validation of US Phone numbers
I'm trying to validate a phone number using preg_match, but any time I type in the correct format of phone number (111) 111-1111, it returns the invalid character error instead of true. I don't think there's anything wrong with my regex (as far as I know), so I'm guessing there's something wrong with my logic
function validate_phone_number($phoneNumber, $requiredLength = 14)
{
//Check to make sure the phone number format is valid
for ($i = 0; $i < strlen($_POST[$phoneNumber]); $i++){
if(preg_match('/^\(\d{3}\) \d{3}-\d{4}\$/', $_POST[phoneNumber]{$i}))
{
return true;
}
else
{
return "<h3>" . "The phone number you entered contains invalid characters" . "</h3>";
}
//Check to make sure the number is the required length
if (strlen($_POST[$phoneNumber]) > $requiredLength) {
return "<h3>" . "The phone number you entered contains too many characters" . "</h3>";
}
else if (strlen($_POST[$phoneNumber]) < $requiredLength) {
return "<h3>" . "The phone number you entered does not contain enough characters" . "</h3>";
}
}
return true;
}
What I'm using to call the function
if (count($_POST) > 0) {
$error = array();
$phone = validate_phone_number('phoneNumber');
if($phone !==true) {
$error[] = $phone;
}
if (count($error) == 0) {
//Phone number validates
}
else {
echo "<h2>Error Message:</h2>";
foreach($error as $msg) {
echo "<p>" . $msg . "</p>";
}
}
}