我正在使用Symfony 1.2.9,我有一个包含两个日期字段的表单:
start_date AND end_date。
我想对'start_date'字段强加以下验证标准:
对于end_date,我想要以下限制:
我写了一个帖子验证器检查如下:
$today = date('Y-m-d');
//post validator check to make sure end date > start date
$this->validatorSchema->setPostValidator(
new sfValidatorAnd(array(
new sfValidatorSchemaCompare('start_date', '<', 'end_date',
array('throw_global_error' => true),
array('invalid' => 'The start date ("%left_field%") must be before the end date ("%right_field%")<br />')
),
new sfValidatorSchemaCompare('start_date', '<', $today,
array('throw_global_error' => true),
array('invalid' => 'The start date ("%left_field%") cannot be earlier than today\'s date: ('.$today.')<br />')
),
new sfValidatorSchemaCompare('end_date', '>', $today,
array('throw_global_error' => true),
array('invalid' => 'The end date ("%left_field%") cannot be before today\'s date ("%right_field%")<br />')
)
)
)
);
然而,这不起作用 - 即我还没有找到根据今天的日期或从今天的日期开始实施限制的方法。
非常欢迎解决方案。
答案 0 :(得分:4)
就个人的代码可读性而言,我会将您的帖子验证检查移动到表单上的postValidate方法,对象:
public function configure()
{
// your normal configuration stuff goes here
// set up your post validator method
$this->validatorSchema->setPostValidator(
new sfValidatorCallback(array(
'callback' => array($this, 'postValidate')
))
);
}
然后您可以执行以下操作:
public function postValidate($validator, $values)
{
$today = date("Y-m-d");
if (strtotime($values["start_date"]) < strtotime($today))
{
$error = new sfValidatorError($validator, "Start date cannot be before than today");
throw new sfValidatorErrorSchema($validator, array('start_date' => $error));
}
if (strtotime($values["start_date"]) > strtotime($values["end_date"]))
{
// throw a similar validation error here
}
// etc...
}