Zend Form Validator:元素A或元素B.

eme*_*ava 13 zend-framework zend-form zend-form-element

我的Zend表单中有两个字段,我想应用验证规则,确保用户输入这两个字段中的任何一个.

    $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);
Run Code Online (Sandbox Code Playgroud)

如何添加一个可以查看这两个字段的验证器?

Dec*_*ler 12

请参阅此页面上的"注意:验证上下文" .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;
    }
}
Run Code Online (Sandbox Code Playgroud)

用法:

$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);
Run Code Online (Sandbox Code Playgroud)