更新时间:2022-12-13 11:43:28
在示例中尝试使用的短名称"验证程序加载仅在您通过验证程序插件管理器注册了该短名称/别名(
The "short name" validator loading you are attempting to use in your example only works if you register that short name / alias with the validator plugin manager (Zend\Validator\ValidatorPluginManager
) first.
一种替代方法(也是我的方式)是在创建表单过滤器对象时注入必要的自定义验证器实例. ZfcUser就是这样的:
One alternative to this (and the way I do it) is to inject instances of necessary custom validators when creating the form filter object. This is the way ZfcUser does it:
// Service factory definition from Module::getServiceConfig
'zfcuser_register_form' => function ($sm) {
$options = $sm->get('zfcuser_module_options');
$form = new Form\Register(null, $options);
$form->setInputFilter(new Form\RegisterFilter(
new Validator\NoRecordExists(array(
'mapper' => $sm->get('zfcuser_user_mapper'),
'key' => 'email'
)),
new Validator\NoRecordExists(array(
'mapper' => $sm->get('zfcuser_user_mapper'),
'key' => 'username'
)),
$options
));
return $form;
},
来源: https://github.com/ZF- Commons/ZfcUser/blob/master/Module.php#L100
在此,将两个ZfcUser\Validator\NoRecordExists
验证器实例(一个用于电子邮件,一个用于用户名)注入到注册表单(ZfcUser\Form\RegisterFilter
)的输入过滤器对象的构造函数中.
Here, the two ZfcUser\Validator\NoRecordExists
validator instances (one for email and one for username) are injected into the constructor of the input filter object for the registration form (ZfcUser\Form\RegisterFilter
).
然后,在ZfcUser\Form\RegisterFilter
类内部,将验证器添加到元素定义中:
Then, inside the ZfcUser\Form\RegisterFilter
class, the validators are added to the element definitions:
$this->add(array(
'name' => 'email',
'required' => true,
'validators' => array(
array(
'name' => 'EmailAddress'
),
// Constructor argument containing instance of the validator
$emailValidator
),
));
来源: https://github.com/ZF-Commons/ZfcUser/blob/master/src/ZfcUser/Form/RegisterFilter.php#L37
我相信另一种选择是使用完全限定的类名作为验证器名称(即:"User \ Validator \ PasswordStrength",而不只是"PasswordStrengthValidator"),尽管我从未尝试过这样做.
I believe another alternative is to use the fully-qualified class name as the validator name (ie: "User\Validator\PasswordStrength" instead of just "PasswordStrengthValidator"), though i've never attempted this myself.