如何在 zend 中以 class 形式添加正则表达式验证器

How to add regex validator in form class in zend

我有一个包含元素的用户表单 class,我正在尝试添加 Regex 验证器。

这是我试过的

$inputFilter->add([
            "name"                   => "password",
            "required"               => true,
            "filters"                => [
            ],
            "validators"             => [
                [
                    "name"           => new Regex(["pattern" => "/^[a-zA-Z0-9_]+$/"]),
                ],
                [
                    "name"           => "NotEmpty",
                ],
                [
                    "name"           => "StringLength",
                    "options"        => [
                        "min"        => 6,
                        "max"        => 64
                    ],
                ],
            ],
        ]);

但是它抛出

Object of class Zend\Validator\Regex could not be converted to string

谁能帮帮我?

您可以为验证器添加输入过滤器规范,以下应该有效

$inputFilter->add([
    "name" => "password",
    "required" => true,
    "filters" => [
    ],
    "validators" => [
        // add validator(s) using input filter specs
        [
            "name" => "Regex",
            "options" => [
                "pattern" => "/^[a-zA-Z0-9_]+$/"
            ],
        ],
        [
            "name" => "NotEmpty",
        ],
        [
            "name" => "StringLength",
            "options" => [
                "min" => 6,
                "max" => 64
            ],
        ],
    ],
]);

如果你真的想实例化对象(使用原始代码中的 new Regex(...)),你可以这样做

$inputFilter->add([
    "name" => "password",
    "required" => true,
    "filters" => [
    ],
    "validators" => [
        // add a regex validator instance 
        new Regex(["pattern" => "/^[a-zA-Z0-9_]+$/"]),
        // add using input filter specs ...
        [
            "name" => "NotEmpty",
        ],
        [
            "name" => "StringLength",
            "options" => [
                "min" => 6,
                "max" => 64
            ],
        ],
    ],
]);

您可能还会发现此 zf 博客 post 很有用 Validate data using zend-inputfilter, as well as the official zend-input-filter docs