13

我的 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);

如何添加一个同时查看两个字段的验证器?

4

4 回答 4

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

用法:

$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);
于 2010-03-09T19:14:41.463 回答
1

@fireeyedboy 提供的解决方案很方便,但不适用于这个确切的问题。

Zend_Validate_Abstract正在使用上下文,它不能作为变量传递给isValid(). 这样,在使用该isValid()方法时(无论是原始的还是覆盖的),空字段都不会被传递和验证(除非你有setRequired(true)or setAllowEmpty(false),这是我们不想要的)。因此,如果您将两个字段 (companynamecompanyother) 都留空,则不会执行任何操作。我知道的唯一解决方案是扩展Zend_Validate类以允许验证空字段。

如果您知道更好的解决方案,请告诉我,因为我也在努力解决类似的问题。

于 2012-04-16T07:49:16.957 回答
0

我同意@chelmertz 的观点,即不存在这样的功能。

我不同意的是扩展Your_Form::isValid()。相反,我会编写一个自定义验证器,它接受两个必须具有值的表单元素的值。这样我就可以在任意表单元素上重用它。这有点类似于 Identical Validator。

于 2010-03-06T21:49:46.180 回答
0

我还没有遇到过这样的解决方案,但它完全有效,所以 +1。

我将扩展Your_Form::isValid()到包括对这两个元素的值的手动检查。

如果所有字段都通过各自的验证器,则此验证可能属于整个表单,因此可以将其放置在表单的验证中而不是字段上。你同意这种思路吗?

于 2010-03-06T19:10:44.793 回答