Welcome Guest, Not a member yet? Register   Sign In
simple evaluation using custom rule
#1

[eluser]mmiranda[/eluser]
Hi, i have a form with start_date and end_date fields, i followed the user guide to setup rules for required and valid_date:

$config = array(
array(
'field' => 'start_date',
'label' => 'Start date',
'rules' => 'trim|required|callback_valid_date'
),
array(
'field' => 'end_date',
'label' => 'End date',
'rules' => 'trim|required|callback_valid_date'
)
);
$this->form_validation->set_rules($config);

so far so good, now i need to validate that start_date < end_date, and show an error if not, to create a hidden field in the form, another callback function just to check if start < end and show form_error('hidden_field_name') seems overkill to me , how can i do that in a simpler way?
#2

[eluser]Mike Ryan[/eluser]
Hi,

You could write a single callback to include this function:
Code:
function date_range_check($str, $field)
    {    
                //$str = 'start_date' value
                //$field = name of 'end_date' field

                $this->form_validation->set_message('date_range_check', 'some message');

                //exit if field is not set
        if (!isset($_POST[$field])) return false;
                //return compare value of dates (simplified - works with unix timestamps)
                return ($str < $_POST[$field]);
    }

Then attach it to one of the date fields:
Code:
$this->form_validation->set_rules('start_date', 'Start date', 'callback_date_range_check[end_date]');

More info
#3

[eluser]TheFuzzy0ne[/eluser]
But you should avoid calling directly on the $_POST array:

Code:
function valid_start_date($str)
{    
    # You should also add some extra validation in here, to ensure that end_date and start_date are the right format.
    if ($str >= $this->input->post('end_date'))
    {
        $this->form_validation->set_message('date_range_check', '% must be more than End Date');
        return FALSE;
    }

    return TRUE;

}

Without knowing the format of the date string, it's hard to be more specific with the validation.
#4

[eluser]Mike Ryan[/eluser]
Thanks for the update Fuzzy - I wasn't sure if $this->input->post('end_date') would be accessible at this point in the validation process. I would still recommend using:
Code:
function valid_start_date($str, $field)
//...
    if ($str >= $this->input->post($field))
though, as it will make the solution more reusable.
#5

[eluser]mmiranda[/eluser]
great, i didnt supose $this->input->post('end_date') is available at validation time, the date format is yyy-mm-dd, so the following should work.

$start = strtotime($start_date);
$end = strtotime($end_date);
if ($start-$end > 0)
return TRUE;
else
return FALSE;




Theme © iAndrew 2016 - Forum software by © MyBB