2

我目前正在验证美国电话号码。问题是下面的代码总是在有效或无效输入之后回显Please enter a valid phone number。我的代码的基本逻辑是我正在检查 preg_match 以查看是否有匹配的有效数字。例子

我该如何解决这个问题,或者有更好的方法来验证电话号码?此外,是否可以回显格式如下的数字:(123)456-7890

PHP

if (isset($_POST['phone'])) {
    if(preg_match('/^(\({1}\d{3}\){1}|\d{3})(\s|-|.)\d{3}(\s|-|.)\d{4}$/',$phone)) {
        echo ('<div id="phone_input"><span id="resultval">'.$phone.'</span></div>');
    }
    else {
        echo '<div id="phone_input"><span id="resultval">Please enter a valid phone number</span></div>';
    }
}
4

1 回答 1

5

尝试这个

<?php
class Validation {
    public $default_filters = array(

        'phone' => array(
            'regex'=>'/^\(?(\d{3})\)?[-\. ]?(\d{3})[-\. ]?(\d{4})$/',
            'message' => 'is not a valid US phone number format.'
        )
    );
    public $filter_list = array();

    function Validation($filters=false) {
        if(is_array($filters)) {
            $this->filters = $filters;
        } else {
            $this->filters = array();
        }
    }

    function validate($filter,$value) {
        if(in_array($filter,$this->filters)) {
            if(in_array('default_filter',$this->filters[$filter])) {
                $f = $this->default_filters[$this->filters[$filter]['default_filter']];
                if(in_array('message',$this->filters[$filter])) {
                    $f['message'] = $this->filters[$filter]['message'];
                }
            } else {
                $f = $this->filters[$filter];
            }
        } else {
            $f = $this->default_filters[$filter];
        }
        if(!preg_match($f['regex'],$value)) {
            $ret = array();
            $ret[$filter] = $f['message'];
            return $ret;
        }
        return true;
    }
}

//example usage
$validation = new Validation();
echo nl2br(print_r($validation->validate('phone','555-555-1212'),true));
echo nl2br(print_r($validation->validate('phone','(555)-555-1212'),true));
echo nl2br(print_r($validation->validate('phone','555 555 1212'),true));
echo nl2br(print_r($validation->validate('phone','555.555.1212'),true));
echo nl2br(print_r($validation->validate('phone','(555).555.1212'),true));
echo nl2br(print_r($validation->validate('phone','(555)---555.1212'),true));//will not match
?>
于 2012-07-28T23:37:10.227 回答