电话号码验证 PHP

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13111864/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 04:47:49  来源:igfitidea点击:

Phone Number Validation PHP

phpvalidationpreg-match

提问by Brian Houlihan

Possible Duplicate:
A comprehensive regex for phone number validation
PHP: Validation of US Phone numbers

可能的重复:
用于电话号码验证的综合正则表达式
PHP:美国电话号码的验证

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

我正在尝试使用 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;
}

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>";
          }
        }
      }

采纳答案by mario

Two things wrong here:

这里有两个错误:

for ($i = 0; $i < strlen($_POST[$phoneNumber]); $i++){
        if(preg_match('/^\(\d{3}\) \d{3}-\d{4}$/', $_POST[phoneNumber]{$i}))

Firstly you used phoneNumberas bare constant. But in the rest of your code you used $phoneNumberas name reference. Change that. (Better yet, pass the $value to your function, not a reference key to $_POST).

首先,您用作phoneNumber裸常量。但是在您用作$phoneNumber名称引用的其余代码中。改变那个。(更好的是,将 $value 传递给您的函数,而不是 $_POST 的引用键)。

Secondly, you seem to be iterating over it character-wise {$i}. But the regex is supposed to be applied to the whole string. Curb the for.

其次,你似乎在迭代它 character-wise {$i}。但是正则表达式应该应用于整个字符串。遏制for

function validate_phone_number($phoneNumber, $requiredLength = 14)
{    
    //Check to make sure the phone number format is valid 
    if (preg_match('/^\(\d{3}\) \d{3}-\d{4}$/', $_POST[$phoneNumber]))
    {

The length check is entirely redundant, as the regex will already assert your fixed format.

长度检查是完全多余的,因为正则表达式已经声明了您的固定格式。

回答by hakre

The two main things I see:

我看到的两个主要事情:

You have a problem with the regular expression:

你的正则表达式有问题:

'/^\(\d{3}\) \d{3}-\d{4}$/'
                        ^- wrong. leave it out:

'/^\(\d{3}\) \d{3}-\d{4}$/'

As you test first for the regular expression, it will only match if the string is exactly 14 characters. Because of that, the check for the string length afterwards is not necessary.

当您首先测试正则表达式时,它只会在字符串正好为 14 个字符时匹配。因此,之后不需要检查字符串长度。

You should also consider to make use of the filter_varfunction, an example:

您还应该考虑使用该filter_var功能,例如:

$options['options'] = array('regexp' => '/^\(\d{3}\) \d{3}-\d{4}$/');
$valid = filter_var($number, FILTER_VALIDATE_REGEXP, $options);

It also has a filter_inputsister function that is able to operate on $_POSTinput. Might be handy:

它还有一个filter_input姊妹函数,可以对$_POST输入进行操作。可能很方便:

$options['options'] = array('regexp' => '/^\(\d{3}\) \d{3}-\d{4}$/');
$valid = filter_input(
    INPUT_POST, 'phoneNumber', FILTER_VALIDATE_REGEXP, $options
);