2009-12-07 55 views
1

我使用Symfony的1.2.9,和我有一个包含两个日期字段的一种形式:Symfony的表单验证日期字段(sfWidgetFormI18nDate)

起始日期日期和结束日期。

我想给予下列验证标准为“起始日期”字段:

  1. 我)。不能少于今天的日期 ii)。不能大于end_date iii)。不能超过1个月 远

对于END_DATE,我想以下限制:

  • i)中。不能超过3个月 从今天远
  • 我已经写了一个帖子验证检查的过程如下:

    $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 />') 
         ) 
        ) 
        ) 
    ); 
    

    但是,这是行不通的 - 即我还没有找到一种方法尚未执行基于今天日期的限制或从今天的日期抵消。

    解决方案将非常受欢迎。

    回答

    4

    亲自为代码的可读性我将你的帖子验证检查到postValidate方法表单上,VIS:

    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... 
    } 
    
    +0

    谢谢,但我有两个问题: 1.您将如何获得表单验证期间触发的'postValidate'方法? 2.您没有使用作为参数传入的验证程序,在伪代码中,查看如何使用传入的验证程序引发验证错误将很有用。 – 2009-12-08 11:54:18

    +0

    编辑解释更多:-) – richsage 2009-12-08 12:37:51

    +0

    非常感谢Ric。对延迟回复你的道歉表示歉意。我会尝试实施它 - 如果它有效,我会接受它作为答案。 – 2009-12-08 16:38:14