开发者

Symfony form validation for date fields (sfWidgetFormI18nDate)

I am using Symfony 1.2.9, and I have a form that contains two date fields:

start_date AND end_date.

I want to impose the following validation criteria for the 'start_date' field:

  1. i). CANNOT be less than todays date ii). CANNOT be greater than end_date iii). CANNOT be more than 1 month away

For end_date, I want the following restrictions:

  1. i). Cannot be more than 3 months away from today

I have written a post validator check as follows:

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

However, this is not working - i.e. I have not found a way yet to enforce restrictions based on todays date, or offsets from today's date.

A solution would be very welcome.


Personally for code readability I'd move your post validation checks into a postValidate method on your form, 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')
    ))
  );
}

Then you can do something like the following:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜