1

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 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

2 Comments

+1 well explained & docs. However, probs a good idea to switch to using FQCN's, e.g. "StringLength::class" instead of "StringLength" - In case of ZF updates that's easier to refactor.
Very well.. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.