1

我在 ZF2 中的输入过滤器有问题。我想要一个只允许数字和缩进 (-) 的输入过滤器。我怎样才能做到这一点?我已经准备好以下代码:

            $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'
                        ),
                    ),
                ),
            ),
        )));
4

2 回答 2

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;
    }

}

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

于 2013-04-08T12:56:04.440 回答
0

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

于 2013-04-08T07:28:26.230 回答