存在一个类Item
。属性为"type
",取值为"a
"、"b
"、"c
"。对于所有类型,都有一个共同的最小属性/输入字段集:type
和其他。每种类型都有一些进一步的属性:
default set of the common fields
type
...
additional fields in case of type=a
foo
additional fields in case of type=b
bar
baz
additional fields in case of type=c
bar
baz
buz
对于type=b
和type=c
, bar
和bar
的验证规则略有不同。
如何根据一个字段(或多个字段)的值在ZF2/Apigilty应用程序中设置验证?对于这个具体的案例:如何根据type
设置验证?
属性type
是依赖于中的属性。这意味着——如果附加字段的集合(foo
, bar
等)与它不匹配,它应该而不是无效。(它是required
,并针对允许的值的数组进行验证,就是这样。)
所以,它应该在相反的方向上工作:
IF (type == 'a') {
proper "required" and validation rules the additional fields
} ELSEIF (type == 'b') {
proper "required" and validation rules the additional fields
} ELSEIF (type == 'c') {
proper "required" and validation rules the additional fields
}
您可以使用自定义逻辑编写ValidTypeInputFilter
,并附加一个类似于以下内容的配置:
array(
'type' => array(
'name' => 'type',
'required' => true,
'validators' => array(
array(
'name' => 'CustomTypeValidator'
)
)
),
'qwer' => array(
'name' => 'qwer',
'required' => true,
'filters' => array(
)
'validators' => array(
)
),
'asdf' => array(
'name' => 'asdf',
'required' => true,
'filters' => array(
)
'validators' => array(
)
),
'yxcv' => array(
'name' => 'yxcv',
'required' => true,
'filters' => array(
)
'validators' => array(
)
)
)
和您的自定义验证器类:
<?php
namespace ApplicationValidator;
class CustomTypeValidator extends AbstractValidator{
const INVALID_TYPE = 'invalid_type';
const NOT_ARRAY = 'not_an_array';
protected $messageTemplates = array(
self::NOT_ARRAY => "Type must be an array",
self::INVALID_TYPE => "Type must be a, b or c",
);
public function isValid($value)
{
$this->setValue($value);
if (!is_array($value)) {
$this->error(self::NOT_ARRAY);
return false;
}
if(key($value) === 'a'){
//... validate a
}
if(key($value) === 'b'){
//... validate b
}
if(key($value) === 'c'){
//... validate c
}
$this->error(self::INVALID_TYPE);
return false;
}
}
对于验证a
, b
和c
,您还可以编写验证器类,并在您的自定义类型验证器中实例化和使用它们:
if(key($value) === 'a'){
$validator = new TypeAValidator():
$valid = $validator->isValid($value['a']);
return $valid;
}