验证邮政编码Zend Framework 2


Validate Zip Code Zend Framework 2

我想验证邮政编码是否对用户有效。我使用的是Zend Framework 2。表单字段类型为"text"(我尝试过值选项,但它似乎不适用于text元素)。有没有一种方法可以在表单或模型(输入过滤器)中验证这一点?我在数据库中有一个邮政编码列表,所以我可以在控制器中使用inArray检查,但如果可能的话,我希望将其包含在模型或表单中。感谢

may be you can write a class in Form folder extend Zend'Validator'AbstractValidator (exmple: zipcodeCheck) and you must implements the function isValid(), you can create some REGEX statement such like :
public function isValid($value){
if(!preg_match(''d{5}([ -]'d{4})?', $value)){// $value is the data you want to validate
    return false;
}
return true;

}

并且您的过滤器必须添加:

$this->add(array(
           'name'        => 'zipcode',
           'validators'  => array(
               array(
                     'name'       => ''Mmc'Form'yourClassName',//zipcodeCheck may be
                     'options'    => array(
                             'error_title'  => 'Zipcode From',
                    )
               )
           ),
    ));

ZF2根据预定义的REGEX模式验证给定的邮政编码(对于美国地区,他们使用以下REGEX模式'''d{5}([-]''d})?')。

因此,如果您通过111111,ZF2总是返回TRUE。

感谢