Zend Framework 2表单自定义验证器 [英] Zend Framework 2 Custom Validators for Forms

查看:92
本文介绍了Zend Framework 2表单自定义验证器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作一个用户注册表格,以检查密码字段的复杂性.我已经根据

I'm trying to make a user registration form which checks for the complexity of the password field. I've written a custom validator to do this according to the documentation. This file lives in my 'User' module at User\src\User\Validator.

<?php

namespace User\Validator;

use Zend\Validator\AbstractValidator;

class PasswordStrength extends AbstractValidator {

const LENGTH = 'length';
const UPPER  = 'upper';
const LOWER  = 'lower';
const DIGIT  = 'digit';

protected $messageTemplates = array(
    self::LENGTH => "'%value%' must be at least 6 characters long",
    self::UPPER => "'%value% must contain at least one uppercase letter",
    self::LOWER => "'%value% must contain at least one lowercase letter",
    self::DIGIT => "'%value% must contain at least one digit letter"
);

public function isValid($value) {
    ... validation code ...
}
}

我的问题出现在尝试在我的用户注册表格中使用此验证器时.我尝试通过在Module.php中配置验证器来将其添加到ServiceManager.

My problem arises in trying to use this validator in my user registration form. I tried adding the validator to the ServiceManager by configuring it in Module.php.

public function getServiceConfig() {
    return array(
        'invokables' => array(
            'PasswordStrengthValidator' => 'User\Validator\PasswordStrength'
        ),
    );
}

然后我将其添加到User.php的输入过滤器中.

Then I added it to the input filter in User.php.

public function getInputFilter() {
    if (!$this->inputFilter) {
        $inputFilter = new InputFilter();
        $factory     = new InputFactory();

        $inputFilter->add($factory->createInput(array(
            'name'     => 'username',
            'required' => true,
            'validators' => array(
                array(
                    'name'    => 'StringLength',
                    'options' => array(
                        'encoding' => 'UTF-8',
                        'min'      => 1,
                        'max'      => 100,
                    ),
                ),
            ),
        )));

        $inputFilter->add($factory->createInput(array(
            'name'     => 'password',
            'required' => true,
            'validators' => array(
                array(
                    'name'    => 'PasswordStrengthValidator',
                ),
            ),
        )));

        $this->inputFilter = $inputFilter;
    }

    return $this->inputFilter;
}

但是,当我访问表单并单击提交"按钮时,会收到ServiceNotFoundException.

However, when I access the form and hit the submit button, I get a ServiceNotFoundException.

Zend\ServiceManager\ServiceManager::get was unable to fetch or create an instance for PasswordStrengthValidator

我的ServiceManager配置是否存在问题?我什至不确定这是否是首先使用自定义验证器的适当方法.我已经找到了许多使用ZF1的示例,但是我发现的ZF2的文档和示例从未超出验证程序的编写范围,无法解决其与表单的集成等问题.任何建议将不胜感激.

Is there a problem with my ServiceManager configuration? I'm not even sure if this is the appropriate way to use a custom validator in the first place. I've found plenty of examples using ZF1, but the documentation and examples for ZF2 that I've found never extend beyond the writing of the validator to address its integration with forms, etc. Any advice would be greatly appreciated.

推荐答案

在示例中尝试使用的短名称"验证程序加载仅在您通过验证程序插件管理器注册了该短名称/别名().

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.

这篇关于Zend Framework 2表单自定义验证器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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