本文介绍了PHP:美国电话号码的验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am currently working with validation of US phone numbers. The issue is that code below is always echoing after a valid or invalid input Please enter a valid phone number . My basic logic of my code is that I am checking with the preg_match to see if there is match for a valid number. Example

该如何解决?还是有更好的方法来验证电话号码?另外,是否有必要回显这样格式化的数字:(123)456-7890?

How can I fix this or is there a better way to validate phone numbers?Also, Is there away to echo the number formatted like this: (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>';
    }
}

推荐答案

尝试一下

<?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
?>

这篇关于PHP:美国电话号码的验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 07:53