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

时间:2009-12-29 10:27:23

标签: php zend-framework forms

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

  • 街道地址
  • 邮政编码
  • 邮局

如果我将每个验证器添加到streetValidator,zipCodeValidator,postOfficeValidator我最终会遇到问题:某处可能有foostreet(验证确定),某处有10101(也可以验证)和某处的barOffice(验证也可以) 。但所有地址信息合起来,没有“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);

但它应该是:

$f = new Zend_Form();
// All three fields are still seperated
$address = new My_Address_Fields();
$address->addValidator(new addressValidator());
$f->addElement($address);

Validator就像

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

1 个答案:

答案 0 :(得分:1)

验证表单元素时,验证程序在$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元素,比如说。

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

优点:它会起作用。