我有一个包含元素的User表单类,并且我正在尝试添加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
],
],
],
]);
但是会抛出
Zend \ Validator \ Regex类的对象无法转换为字符串
有人可以帮我吗?
答案 0 :(得分:3)
您可以为验证器添加输入过滤器规格,以下应该可以使用
$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博客文章Validate data using zend-inputfilter和官方zend-input-filter docs有用