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?

Ali Rasheed
  • 2,765
  • 2
  • 18
  • 31

1 Answers1

3

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

Crisp
  • 11,417
  • 3
  • 38
  • 41
  • 1
    +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. – rkeet Jan 29 '19 at 07:59
  • Very well.. Thanks. – Ali Rasheed Jan 29 '19 at 08:43