"password"" /> "password"" /> "password""/>

How to add regex validator in form class in zend

441 views Asked by At

I have a User form class which has elements and I am trying to add Regex validator.

Here is what I have tried

$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
                    ],
                ],
            ],
        ]);

But it throws

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

Can anyone help me out?

1

There are 1 answers

2
Crisp On BEST ANSWER

You can add input filter specifications for the validator, the following should work

$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
            ],
        ],
    ],
]);

If you really want to instantiate the object (using the new Regex(...) as in your original code), you can do that this way instead

$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
            ],
        ],
    ],
]);

You may also find this zf blog post useful Validate data using zend-inputfilter, as well as the official zend-input-filter docs