ZF2:允许空字段集,但验证是否填写了至少一个

时间:2013-08-22 14:04:01

标签: validation zend-framework2 fieldset

我为电话号码定义了一个字段集。其中包含“type”(私有,Office mobile ...)和“number”字段。数字的输入过滤器是“required => true”:

``

class PhoneFieldset extends BaseFieldset implements InputFilterProviderInterface
{

  public function __construct()
  {
    parent::__construct('phones');

    $this->setHydrator(new DoctrineHydrator($this->getEntityManager(), 'HtsBase\Entity\Phone'))
            ->setObject(new Phone());

    $this->add(array(
        'type' => 'DoctrineORMModule\Form\Element\EntitySelect',
        'name' => 'type',
        'options' => array(
            'label' => 'Type',
            'empty_option' => '',
            'object_manager' => $this->getEntityManager(),
            'target_class' => 'HtsBase\Entity\OptionlistPhoneType',
            'property' => 'name',
        ),
        'attributes' => array(
            #'id' => 'type',
            'class' => 'input-medium',
        ),
    ));

    $this->add(array(
        'name' => 'number',
        'options' => array(
            'label' => 'Number',
        ),
        'attributes' => array(
            'type' => 'text',
            #'id' => 'number',
            'class' => 'input-medium',
            'maxlength' => '25',
            'autocomplete' => 'off',
        ),
    ));
  }

  public function getInputFilterSpecification()
  {
    return array(
        'type' => array(
            'required' => false,
        ),
        'number' => array(
            'required' => true,
            'filters' => array(
                array('name' => 'StringTrim'),
            ),
            'validators' => array(
                array(
                    'name' => 'StringLength',
                    'options' => array(
                        'encoding' => 'UTF-8',
                        'max' => 25,
                    ),
                ),
            ),
        ),
    );
  }

``

我可以在整个字段集中附加验证器/过滤器吗?因此,如果“type”和“number”为空,则fieldset有效,但验证是否填写了至少一个?

1 个答案:

答案 0 :(得分:1)

我找到了一个易于使用的解决方案,虽然我不再使用该表单,但我现在大量使用InputFilter并且仍然需要相同的东西。但找到了一个简单的解决方案

AbstractFilterValidator,我自己的实现

abstract class AbstractFilterValidator extends AbstractValidator
{
    /**
     * Returns true if and only if $value meets the validation requirements
     *
     * If $value fails validation, then this method returns false, and
     * getMessages() will return an array of messages that explain why the
     * validation failed.
     *
     * @param  mixed $value
     * @return bool
     * @throws Exception\RuntimeException If validation of $value is impossible
     */
    public function isValid($value)
    {
        $this->setValue($value);
        $filter = $this->buildFilter();
        $filter->setData($value);

        if (!$filter->isValid()) {
            $this->abstractOptions['messages'] = $filter->getMessages();
            return false;
        }
        return true;
    }

    /**
     * @return array
     */
    public function getMessages()
    {
        return $this->abstractOptions['messages'];
    }

    /**
     * @return InputFilter\InputFilter
     */
    abstract protected function buildFilter();
}

旧答案

虽然您使用的是InputFilterProviderInterface,但我使用的是Zend\InputFilter\InputFilter,并且想要和您一样。如果未填写字段集,请验证true

为此,我将isValid替换为以下内容;

public function isValid()
{
    $values = array_filter($this->getRawValues());
    if (empty($values)) {
        return true;
    }

    return parent::isValid();
}

它只是从所有空数组键中过滤数组,有关该信息,请参阅docs。然后检查$values是否为空,如果是,则返回true。否则验证验证器。


嗯,我又需要一些东西,但需要一个像样的解决方案。仍然没有找到一个好的运气,所以我写了下面的代码。

<?php
namespace Application\InputFilter;

use Zend\InputFilter as ZFI;

class InputFilter extends ZFI\InputFilter
{
    private $required = true;

    /**
     * @return boolean
     */
    public function isRequired()
    {
        return $this->required;
    }

    /**
     * @param boolean $required
     *
     * @return $this
     */
    public function setRequired($required)
    {
        $this->required = (bool) $required;
        return $this;
    }

    /**
     * @return bool
     */
    public function isValid()
    {
        if (!$this->isRequired() && empty(array_filter($this->getRawValues()))) {
            return true;
        }

        return parent::isValid();
    }
}

github gist

您现在可以在setRequired(false)

上致电InputFilter