我的ZF2中的inputfilter出现问题。我想要一个只允许数字和缩进( - )的inputfilter。我该怎么做?我已经完成了以下代码:
$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 :(得分: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;
}
}
然后我像其他任何验证器一样使用它...希望这有帮助!
答案 1 :(得分:0)
将您的模式更改为/^[\d-]+$/
- 它应该会有所帮助。