我正在努力根据名为 published
的字段实体来执行验证问题。我必须应用验证规则:
- 当实体设置为
true
时验证实体 - 设置为
false
时不执行任何操作(草稿功能)
我设法将回调验证器添加到规范字段中,该字段检查我的规则并且它有效 很好:
Validator definition
$emptyValidatorOnPublish = array(
'name' => 'Callback',
'options' => array(
'messages' => array(
\Zend\Validator\Callback::INVALID_VALUE => 'This field cannot be empty',
),
'callback' => function($value, $context=array()) {
if($context['published']){//Here I know the POST value
return !empty($value); //it must not be empty
}
return true;
},
),
);
用法:
array(
'name' => 'title',
'description' => 'Title of the interview',
'required' => true,
'filters' => array(
0 => array(
'name' => 'Zend\\Filter\\StringTrim',
'options' => array()
),
1 => array(
'name' => 'Zend\\Filter\\StripTags',
'options' => array()
)
),
'validators' => array($emptyValidatorOnPublish),
'error_message' => 'title is required',
'allow_empty' => true,
'continue_if_empty' => true
)
现在我在一些字段上使用 ObjectExists
进行验证验证器:
array(
'name' => 'person',
'description' => 'Person link',
'required' => true,
'filters' => array(),
'validators' => array(
0 => array(
'name' => 'MyApp\\Validators\\ObjectExists',
'options' => array(
'fields' => 'ref',
'message' => 'This person does not exist',
'object_manager' => 'doctrine.entitymanager.orm_default',
'object_repository' => 'MyApp\\Person'
)
)
),
'allow_empty' => true,
'continue_if_empty' => true
),
ObjectExists
验证器扩展 DoctrineModule\Validator\ObjectExists
.
class ObjectExists extends BaseObjectExists
{
/**
* {@inheritDoc}
*/
public function isValid($value)
{
if (! is_array($value)) {
return parent::isValid($value);
}
$isValid = null;
foreach ($value as $oneValue) {
$isValid = false === $isValid ? $isValid : parent::isValid($oneValue);
}
return $isValid;
}
}
问题:
父类验证器不知道
published
的值即使我更改实现来检查
published
value 我将从数据库中获取值,而不是从实际的POST
中获取值请求
有没有办法根据 published
检查实体是否存在请求的值?
有没有办法在验证另一个字段时传递同级值(在我的例子中,在验证 'published
时传递 person
)?
最佳答案
你的输入过滤器有一个叫做 validation group 的东西。 。当您的 published
字段的值为 false
且这些输入元素未得到验证时,您可以从该验证器组中删除您不想验证的输入当输入过滤器运行时。
您不必在验证器类本身中解决这个问题。最好将此逻辑移至更高级别(例如,通过在输入过滤器类的 init
方法中设置验证组)。我认为验证器类本身不应该承担这个责任。
//pass the input names you want to validate here when published is false
if($published === false){
$inputFilter->setValidationGroup();
}
在这样的解决方案中,您只需将此 published
字段注入(inject)您的输入过滤器类中,而不是在所有单独的验证器中。
关于php - Zend 2 条件验证器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41869414/