Date validation with 3 inputs select

Hi,

What is the proper way to validate (\Phalcon\Validation*) a date with many fields?

When you use one field, it's easy... But if I use, 3 inputs select... You must validate year/month/day in a range. But it's better to check the exact date...

Any tip / idea / existing tool?

Thanks!

EM



1.7k

I created an hack in the form class. It's dirty, but it works.

    public function beforeValidation(array $data)
    {
        if(!isset($data['year'])) {
            return;
        }

        $date = sprintf(
            '%d-%02d-%02d',
            (int) $data['year'],
            (int) $data['month'],
            (int) $data['day']
        );

        $validation  = new \Phalcon\Validation();
        $validation->add('lol', new Date_Validator(['format' => 'Y-m-d']));
        $element_messages = $validation->validate(['lol' => $date]);

        $messages = [];
        if(count($element_messages) > 0) {
            $messages['lol'] = $element_messages;
            $this->_messages = $messages;
            return false;
        }
        return true;
    }
edited Jun '16

Why do you have your validation in your beforeValidation method? All you need is the data transformation on the form item.

  public function beforeValidation(array $data)
  {
    $this->date = sprintf(
      '%d-%02d-%02d',
      (int) $data['year'],
      (int) $data['month'],
      (int) $data['day']
    );
  }

validation on your date field will handle the rest in your initialize.

public function initialize()
{
    $date->addValidators(array(
        new Date_Validator(array( 'message' => 'The name is required' ))
    ));
}

you coudl also include your other fields on your form so you can use your form->render() methods in volt if you are using it. then you coudl keep everythign inside the module.

public function initialize()
{
  $this->add(new Text('year'));
  $this->add(new Text('month'));
  $this->add(new Text('day'));

  $date = new Date();
  $date->addValidators(array(
      new Date_Validator(['format' => 'Y-m-d'])
  ));
  $this->add($date);
}

 public function beforeValidation()
  {
    $this->date = sprintf(
      '%d-%02d-%02d',
      (int) $this->year,
      (int) $this->month,
      (int) $this->day
    );
  }