使用Zend Framework验证多个可选表单字段 [英] Validating multiple optional form fields with Zend Framework

查看:80
本文介绍了使用Zend Framework验证多个可选表单字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试验证Zend_Form,它具有多个可选字段,并且我希望至少填写其中一个.在我的情况下,我具有手机,家庭和办公室电话号码,并且我希望至少提供其中一个.

I am trying to validate Zend_Form which has several optional fields and I want at least one of them to be filled in. In my case I have mobile, home and office phone numbers and I want at least one of them to be provided.

我正在尝试通过验证上下文"来实现这一点(如建议的此处),方法是创建扩展Zend_Validate_Abstract的自定义验证程序.问题在于,如果所有可选字段均为空,则它们会以$ context形式丢失(传递给验证器类),并且这种方式根本不会得到验证. 因此,如果您填写了三个选项中的任何一个或几个(移动设备,家庭,工作),则将全部进行验证(这很好,但是为此不需要自定义验证器),但是如果您都不填写,则有没有选择强迫客户填写至少一个字段(这是我的目标).

I am trying to achieve this though Validation Context (as suggested here) by creating custom validator which extends Zend_Validate_Abstract. The problem is that if all optional fields are empty they are missing from the form $context (passed to the validator class) and this way not validated at all. So if you fill any or several of the three options (mobile, home, work) they are all going to be validated (which is fine, but for this no custom validator is needed), but if you fill none of them, there is no option to force the customer to fill at least one of the fields (which is my aim).

这就是我所拥有的:

<?php

class Application_Form_Application extends Zend_Form {

  public function init() {
    $this->setName('application');

    // attach sub forms to main form
    $this->addSubForms(array(
      'application' => $this->application(),
      ...
    ));
  }

  private function application() {
    $application = new Zend_Form_SubForm();
    // custom phone validation
    $phone_validation = array('phone_mobile' => 'Mobile', 'phone_home' => 'Home', 'phone_work' => 'Work');
    // phone mobile
    $app['phone_mobile'] = new Zend_Form_Element_Text('phone_mobile');
    $app['phone_mobile']->setLabel('Mobile')
                        ->addFilter('StripTags')
                        ->addFilter('StringTrim')
                        ->addValidator('Regex', false, array('/^[0-9]{8}$/i'))
                        ->addValidator(new Application_Form_PhoneMobileHomeWork($phone_validation), false);
    // phone home
    $app['phone_home'] = new Zend_Form_Element_Text('phone_home');
    $app['phone_home']->setLabel('Home')
                      ->addFilter('StripTags')
                      ->addFilter('StringTrim')
                      ->addValidator('Regex', false, array('/^[0-9]{8}$/i'))
                      ->addValidator(new Application_Form_PhoneMobileHomeWork($phone_validation), false);
    // phone work
    $app['phone_work'] = new Zend_Form_Element_Text('phone_work');
    $app['phone_work']->setLabel('Work')
                      ->addFilter('StripTags')
                      ->addFilter('StringTrim')
                      ->addValidator('Regex', false, array('/^[0-9]{8}$/i'))
                      ->addValidator(new Application_Form_PhoneMobileHomeWork($phone_validation), false);
    $application->AddElements($app);
  }

}
?>

2.自定义验证器

<?php

class Application_Form_PhoneMobileHomeWork extends Zend_Validate_Abstract {

  const NOT_PRESENT = 'notPresent';

  protected $_messageTemplates = array(
    self::NOT_PRESENT => 'At least one contact phone shall be provided!'
  );

  protected $_listOfFields;

  public function __construct(array $listOfFields) {
    $this->_listOfFields = $listOfFields;
    var_dump($listOfFields);exit;
  }

  public function isValid($value, $context = null) {
    var_dump($context);exit;
    ...
  }
?>

验证器总是通过第一个转储($ listOfFields),但是如果我删除它,除非在某些电话字段中键入某些数据(我们要防止),否则永远不会调用isValid().

The validator always passes though the first dump ($listOfFields), but if I remove it, isValid() is never called unless some data is typed into some of the phone fields (which we want to prevent).

当我进一步检查时,我发现了一种解决方案,可以通过将空字段传递给$ context参数来扩展Zend_Validate类,但是如果有人知道,我希望有一个更好的解决方案.

When I checked further I found a solution in extending the Zend_Validate class by passing empty fields to the $context parameter, but I would like to have a better solution if someone knows any.

简而言之-如何验证某些表格,迫使用户填写几个可选字段中的至少一个?

Concluding it in short - how to validate certain form, forcing the user to fill at least one out of several optional fields?

推荐答案

如果我理解正确,则希望不要使用表单元素,但要防止它们为空(除非其中一个不为空),请使用定制验证器?然后,为了不跳过验证链,您需要防止在每个元素中调用方法setAllowEmpty(false)来使它们为空.

If I understand you right, you want your form elements to not be required, but prevent them to be empty (except if one of them is not empty) using a custom validator? Then, in order to not skip the validation chain, you need to prevent them to be empty calling the method setAllowEmpty(false) in each of your elements.

最后,在您的自定义验证器中,您将得到以下内容:

Finally, in your custom validator, you will have something like this:

foreach ($this->_listOfFields as $field) {
    if (isset($context[$field]) AND $context[$field])
    {
        return true;
    }
}

此外,请确保不需要您的元素(setRequired(false)).

Also, make sure your elements are not required (setRequired(false)).

这篇关于使用Zend Framework验证多个可选表单字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆