可能重复:
电话号码验证的综合正则表达式
PHP:美国电话号码验证
我正在尝试使用 preg_match 验证电话号码,但任何时候我输入正确格式的电话号码 (111) 111-1111,它都会返回无效字符错误而不是 true。我认为我的正则表达式没有任何问题(据我所知),所以我猜我的逻辑有问题
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;
}
我用来调用函数的内容
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>";
}
}
}