2012-07-28 242 views
2

我目前正在驗證美國電話號碼。問題是下面的代碼總是在有效或無效輸入Please enter a valid phone number後回顯。我的代碼的基本邏輯是我正在檢查preg_match以查看是否有匹配的有效數字。 ExamplePHP:驗證美國電話號碼

我該如何解決這個問題,還是有更好的方法來驗證電話號碼? 此外,有沒有回顯數字格式如下:(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>'; 
    } 
} 
+0

只是刪除非數字並根據需要對其進行格式化格式化。像我這樣懶惰的人不喜歡輸入標點符號。 – 2012-07-28 23:37:23

回答

4

嘗試這個

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

請勿使用ereg。它[已棄用](http://php.net/ereg)。 – Lusitanian 2012-07-28 23:43:44

+0

但是如果有人喜歡把自己的電話號碼寫成2234567890或(223)-555-9191或(445)333-6969怎麼辦? – 2012-07-28 23:44:04

+0

爲什麼'if(x)返回true;否則返回false;'?只是'返回x;'。 (不是說這應該永遠用於驗證電話號碼......) – Ryan 2012-07-28 23:50:23