简体   繁体   中英

Validation rule for a days time lapse in codeigniter?

I have a form with two date fields, these fields define a time period, characterized by a starting date and an ending date, instead of forcing the user to type a date, I´m using a javascript date selector for those dates, I have validation rules for each field through callbacks, like this:

    $this->form_validation->set_rules('fechainicio', 'Fecha de Inicio', 'required|callback_startDate_valid');
    $this->form_validation->set_rules('fechafin', 'Fecha de Fin', 'required|callback_endDate_valid');

The rules work Ok, individually, no problem! but as these fields define a (days) time period, I need the starting date to be older than the ending date, this would be my 3rd validation rule, but, how do I do this if the date fields are separate? If I use the post values, they are only known after dates have been chosen, this causes an initial error (unknown array index) because the fields are empty when you load the form intially, any idea? thanx ia

you can take value of start date inside your endDate function.

function endDate_valid($endDate)
{
  $startDate = $this->input->post('fechainicio');

  if($startDate > $endDate){
    $this->form_validation->set_message('endDate_valid','End Date must be greater than start date');
    return FALSE;
  }
  return TRUE;
}

I solved it by testing the dates before they reach the dates, this way:

if (isset($_POST['save'])){
        $post_data = array();
        if( $this->input->post() ){
            $post_data = $this->input->post();
            if( $post_data['fechainicio'] < $post_data['fechafin'] ){
                $data['fechaUno'] = $post_data['fechainicio'];
                $data['fechaDos'] = $post_data['fechafin'];
            }else{
                echo "There´s an error in dates order.";
            }
        }
    }

though I see some redundance in isset($_POST['save']) and the if( $this->input->post() ) condition, anyway it worked, I just tried @jagad89 tip and works great!, thanx!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM