zend-framework – Zend Form验证器:元素A或元素B
发布时间:2020-12-13 13:59:58 所属栏目:PHP教程 来源:网络整理
导读:我的Zend Form中有两个字段,我想应用验证规则,确保用户输入这两个字段之一. $companyname = new Zend_Form_Element_Text('companyname'); $companyname-setLabel('Company Name'); $companyname-setDecorators($decors); $this-addElement($companyname); $c
我的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调用作为第二个参数.所以只需编写自己的分析上下文的验证器.
编辑: 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); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |