我的Zend Form中有两个字段,我想应用验证规则,确保用户输入这两个字段之一.
$companyname = new Zend_Form_Element_Text('companyname'); $companyname->setLabel('Company Name'); $companyname->setDecorators($decors); $this->addElement($companyname); $companyother = new Zend_Form_Element_Text('companyother'); $companyother->setLabel('Company Other'); $companyother->setDecorators($decors); $this->addElement($companyother);
我如何添加一个验证器来查看这两个字段?
请参阅此
page上的“注意:验证上下文”.Zend_Form将上下文传递给每个Zend_Form_Element :: isValid调用作为第二个参数.所以只需编写自己的分析上下文的验证器.
原文链接:https://www.f2er.com/php/139476.html编辑:
好的,我以为我自己拍了拍.它没有测试,也不是一切手段,但它会给你一个基本的想法.
class My_Validator_OneFieldShouldBePresent extend Zend_Validator_Abstract { const NOT_PRESENT = 'notPresent'; protected $_messageTemplates = array( self::NOT_PRESENT => 'Field %field% is not present' ); protected $_messageVariables = array( 'field' => '_field' ); protected $_field; protected $_listOfFields; public function __construct( array $listOfFields ) { $this->_listOfFields = $listOfFields; } public function isValid( $value,$context = null ) { if( !is_array( $context ) ) { $this->_error( self::NOT_PRESENT ); return false; } foreach( $this->_listOfFields as $field ) { if( isset( $context[ $field ] ) ) { return true; } } $this->_field = $field; $this->_error( self::NOT_PRESENT ); return false; } }
用法:
$oneOfTheseFieldsShouldBePresent = array( 'companyname','companyother' ); $companyname = new Zend_Form_Element_Text('companyname'); $companyname->setLabel('Company Name'); $companyname->setDecorators($decors); $companyname->addValidator( new My_Validator_OneFieldShouldBePresent( $oneOfTheseFieldsShouldBePresent ) ); $this->addElement($companyname); $companyother = new Zend_Form_Element_Text('companyother'); $companyother->setLabel('Company Other'); $companyother->setDecorators($decors); $companyname->addValidator( new My_Validator_OneFieldShouldBePresent( $oneOfTheseFieldsShouldBePresent ) ); $this->addElement($companyother);