我有一个包含两个日期的表单,即开始和结束。我有一个验证器用于启动,我想验证停止,并且该停止是在启动之后。但是,如果开始有效,则后验证才有意义。
isValid($value, $context = null)
可以传递给上下文变量中的其他值,但是我必须再次进行开始检查。
那么有可能在停止验证器的isValid()
函数中检查启动验证的结果吗?
答案 0 :(得分:2)
您可以使用Callback
或者只写下您的own validator
------编辑 - 我提出的答案 - 带回调或验证器的输入过滤器------
我是这样做的。
首先创建一个包含所有参数的过滤器:
namespace MyGreatNameSpace\Filter;
use Zend\InputFilter\InputFilter;
use Zend\InputFilter\Factory as InputFactory;
class MyDateFilter extends InputFilter
{
public function __construct($myGreatClass)
{
$factory = new InputFactory();
$this->add($factory->createInput(array(
'name' => 'start_date',
'required' => true,
'validators' => array(
array(
'name' => 'Date',
'options' => array(
'format' => '2000-10-10',
),
)
),
)));
$this->add($factory->createInput(array(
'name' => 'end_date',
'required' => true,
'validators' => array(
array(
'name' => 'Date',
'options' => array(
'format' => '2000-10-10',
),
),
array(
'name' => 'Callback',
'options' => array(
'callback' => array($myGreatClass, 'isDateNewer'),
'messages' => array(
'callbackValue' => "The end date is Older then the start date",
),
),
),
),
)));
} // End of __construct
}
public function isDateNewer($date, $params)
{
$date2 = $params['start_date'];
if ($date > $date2) { // Over simplistic
return TRUE;
}
}
在控制器中植入(我使用服务来拉取表单/过滤器类)
// Get the form / validator objects from the SM
$form = $this->getServiceLocator()->get('date_form');
$filter = $this->getServiceLocator()->get('date_filter');
// Inject the input filter object to the form object, load the form with data and bind the result to the model
$form->setInputFilter($filter);
$form->setData($post);
$form->bind($myModel); // (if you wish to bind the data to whatever)
if (!$form->isValid()) {
return $this->forward()->dispatch.... (or whatever)
}
另一种略微不同的方式(虽然更干净)是编写验证器。检查Zend\Validator\Identical(注意令牌)
array(
'name' => '\Application\Validator\myNewNamedValidator',
'options' => array(
'token' => 'start_date',
'messages' => array(
'older' => "The end date is Older then the start date",
),
),
),