Php 如何将多个元素组合到一个验证器?

Php 如何将多个元素组合到一个验证器?,php,zend-framework,forms,Php,Zend Framework,Forms,如何将多个表单元素组合到一个验证器?我有地址信息,包括 街道地址 邮政编码 邮局 如果我将验证器添加到它们中的每一个,如streetValidator、zipCodeValidator、postOfficeValidator,我最终会遇到问题:可能在某个地方有foostreet(验证ok)、10101(验证ok)和barOffice(验证ok)。但是所有的地址信息加起来,没有“foostreet,10101,barOffice”的地址 现在你有: <?php $f = new Zend

如何将多个表单元素组合到一个验证器?我有地址信息,包括

  • 街道地址
  • 邮政编码
  • 邮局
如果我将验证器添加到它们中的每一个,如streetValidator、zipCodeValidator、postOfficeValidator,我最终会遇到问题:可能在某个地方有foostreet(验证ok)、10101(验证ok)和barOffice(验证ok)。但是所有的地址信息加起来,没有“foostreet,10101,barOffice”的地址

现在你有:

<?php
$f = new Zend_Form();

$street = new Zend_Form_Element_Text('street');
$f->addElement($street);

$zip = new Zend_Form_Element_Text('zip');
$f->addElement($zip);

$office = new Zend_Form_Element_Text('office');
$f->addElement($office);
验证器类似于

class addressValidator extends Zend_Validator_Abstract
{
  public function isValid()
  {
    //$street = ???;
    //$zip = ???;
    //$office = ???;

    // XMLRPC client which does the actual check
    $v = new checkAddress($street, $zip, $office);
    return (bool)$v->isValid();
  }
}

验证表单元素时,
$context
参数内的所有表单值都将提供给验证器。因此,您的验证器可以如下所示:

  public function isValid( $value, $context = null )
  {
    $street = ( isset($context['street']) )? $context['street'] : null;
    $zip =    ( isset($context['zip']) )?    $context['zip']    : null;
    $office = ( isset($context['office']) )? $context['office'] : null;

    // XMLRPC client which does the actual check
    $v = new checkAddress($street, $zip, $office);
    return (bool)$v->isValid();
  }
然后,将验证器添加到
street
元素中,比如说

缺点:这个验证器有点脱离实体,附加到一个特定的元素,但不是真正的


优点:它可以工作。

因为没有
Zend\u Validate\u摘要::\uu构造()
需要注意,可以使用该方法进行映射,即
您的\u Validate::\uu构造($mapping=array())
类似于
$mapping['streetElementId']='street'
,反过来,方法
您的_Validate::isValid()
会知道验证每个元素的规则。我想是关于如何创建MyAddressField的部分导致了问题。为了创建复合表单元素,您必须将装饰器分层。退房。尤其是链接为<代码>文章<代码>的文章,应该会让你进入
  public function isValid( $value, $context = null )
  {
    $street = ( isset($context['street']) )? $context['street'] : null;
    $zip =    ( isset($context['zip']) )?    $context['zip']    : null;
    $office = ( isset($context['office']) )? $context['office'] : null;

    // XMLRPC client which does the actual check
    $v = new checkAddress($street, $zip, $office);
    return (bool)$v->isValid();
  }