在我的 Zend Framework 2 Form 类中,我像这样添加我的元素:
$this->add(array(
'name' => 'passwordConfirm',
'type' => 'Password',
'attributes' => array(
'required' => 'required',
'placeholder' => 'Confirm password',
),
'options' => array(
'label' => 'Confirm password',
'column-size' => 'sm-10',
'label_attributes' => array(
'class' => 'col-sm-2',
),
),
'validators' => array(
array(
'name' => 'NotEmpty',
),
array(
'name' => 'Identical',
'options' => array(
'token' => 'password',
),
),
),
));
正如官方参考中所述。我创建表单的新实例,如下所示:
$form = $this->getServiceLocator()->get('user.auth.form');
$hydrator = new DoctrineHydrator($this->entityManager());
$form->setHydrator($hydrator);
$form->bind($user);
但是,validators
不会添加到元素验证器链中。这是var_dump($form->get('passwordConfirm'));
的输出
object(Zend'InputFilter'Input)[506]
protected 'allowEmpty' => boolean true
protected 'continueIfEmpty' => boolean false
protected 'breakOnFailure' => boolean false
protected 'errorMessage' => null
protected 'filterChain' =>
object(Zend'Filter'FilterChain)[507]
protected 'plugins' => null
protected 'filters' =>
object(Zend'Stdlib'PriorityQueue)[508]
protected 'queueClass' => string 'Zend'Stdlib'SplPriorityQueue' (length=28)
protected 'items' =>
array (size=0)
...
protected 'queue' => null
protected 'options' =>
array (size=0)
empty
protected 'name' => string 'passwordConfirm' (length=15)
protected 'notEmptyValidator' => boolean false
protected 'required' => boolean false
protected 'validatorChain' =>
object(Zend'Validator'ValidatorChain)[509]
protected 'plugins' => null
protected 'validators' =>
array (size=0)
empty
protected 'messages' =>
array (size=0)
empty
protected 'value' => null
protected 'fallbackValue' => null
protected 'hasFallback' => boolean false
当我为验证器输入无效输入时,$form->isValid()
可以毫无问题地接受表单。
我做错了什么?
在查看源代码并使用此语法尝试其他一些事情后,我发现您根本无法从 Zend Framework 2.3 开始使用此数组语法添加验证器。我上面引用的官方文档中的示例是完全错误的。
对于验证,请使用参考中关于Zend'Validator
部分中描述的更详细的语法。