2013-04-08 38 views
1

我的ZF2输入过滤器出现问题。我想要一个只允许数字和缩进( - )的inputfilter。我怎么能做到这一点?我有媒体链接下面的代码:phonenumber Zend的输入过滤器(正则表达式)

  $inputFilter -> add($factory -> createInput(array(
      'name' => 'phonenumber', 
      'required' => false, 
      'filters' => array(
       array('name' => 'Int'), 
      ), 
      'validators' => array(
       array(
        'name' => 'regex', false, 
        'options' => array(
         'pattern' => '/\([0-9]{3}\)\s[0-9]{3}-[0-9]{4}/', 
         'messages'=>array(\Zend\Validator\Regex::NOT_MATCH=>'%value% is not a valid phone' 
         ), 
        ), 
       ), 
      ), 
     ))); 

回答

0

您的模式更改为/^[\d-]+$/ - 它应该帮助。

+0

这是我认为正确的模式,但如何设置验证器的权利。我认为这不是正确的方式,还没有工作。 – Haidy 2013-04-08 07:49:48

1

对于电话号码,我创建了是这样的我自己Zend_Validate_Phone文件:

<?php 
/** 
* Zend_Validate_Phone 
* 
* A validator that can be used in Zend_Form to validate phone numbers 
* Accepts only north-american form numbers 
* 
* Accepted: 
* (819)800-0755 
* 819-800-0755 
* 8198000755 
* 819 800 0755 
*/ 

/** 
* @see Zend_Validate_Abstract 
*/ 
require_once 'Zend/Validate/Abstract.php'; 

class Zend_Validate_Phone extends Zend_Validate_Abstract 
{ 
    const INVALID  = 'phoneInvalid'; 
    const STRING_EMPTY = 'phoneStringEmpty'; 

    /** 
    * Validation failure message template definitions 
    * 
    * @var array 
    */ 
    protected $_messageTemplates = array(
     self::INVALID  => "Invalid phone number. Make sure this is a valid north american phone number (xxx)xxx-xxxx", 
     self::STRING_EMPTY => "'%value%' is an empty string", 
    ); 

    /** 
    * Sets default option values for this instance 
    * 
    * @return void 
    */ 
    public function __construct() { 

    } 

    /** 
    * Defined by Zend_Validate_Interface 
    * 
    * Returns true if and only if $value contains a valid phone number 
    * 
    * @param string $value 
    * @return boolean 
    */ 
    public function isValid($value) {  
     //A regex to match phone numbers 
     $pattern = "((\(?)([0-9]{3})(\-| |\))?([0-9]{3})(\-)?([0-9]{4}))"; 

     //If regex matches, return true, else return false 
     if(preg_match($pattern, $value, $matches)) { 
      //Valid phone number 
      $isValid = true; 
     } else { 
      $this->_error(self::INVALID); 
      $isValid = false; 
     } 


     return $isValid; 
    } 

} 

然后我使用它像任何其他验证...希望这会有所帮助!

+0

今天去看看这个,谢谢;) – Haidy 2013-04-09 08:51:33