Reputation: 50
I want to use a function to validate dates with a parameter...but I have all validations in a config array.
config = array(
'page1/send' => array(
array(
'field' => 'name',
'label' => 'lang:name',
'rules' => 'required'
)
),
'page2/send' => array(
array(
'field' => 'name',
'label' => 'lang:name',
'rules' => 'required'
),
array(
'field' => 'date1',
'label' => 'lang:date',
'rules' => 'required|'
)
array(
'field' => 'date2',
'label' => 'lang:date',
'rules' => 'required|callback_date_compare'
)
),
I would like to pass an additional parameter to "callback_date_compare" in this case the other field (date1).
Without setting the rules in an array I could do it in this way if "$date1" is the value of the post['date1'] and it worked perfectly :
$this->form_validation->set_rules('date2', 'lang:date', 'required|callback_date_compare[' . $date1 . ']');
I need to do it inside the array because I have all validations inside it and I tried to do it the same way inside the $config array but it didn´t work, something like:
array(
'field' => 'date2',
'label' => 'lang:date',
'rules' => 'required|callback_date_compare[date1]'
)
Any help is appreciated.
Upvotes: 0
Views: 5086
Reputation: 10996
Since your config is global, it might be a good idea to have the function global aswell.
Create MY_Form_validation.php
in libraries/
:
<?php
class MY_Form_validation extends CI_Form_validation {
function date_compare($str_start, $str_key) {
$bool = ($str_start == $this->input->post($str_key));
if ( ! $bool)
$this->form_validation->set_message('date_compare', 'Dates are different');
return $bool;
}
}
Then set the rule date_compare[date1]
.
Upvotes: 1
Reputation: 60048
In your config array
array(
'field' => 'date2',
'label' => 'lang:date',
'rules' => 'required|callback_date_compare[date1]'
)
in your date compare callback
function date_compare($value, $field_name)
{
// Get the value in the field
$field = $_POST[$field_name];
if ($value != $this->input->post($field))
{
$this->form_validation->set_message('date_compare', 'Dates are different');
return FALSE;
}
else
{
return TRUE;
}
}
Upvotes: 3
Reputation: 1694
create a function called date_compare:
public function date_compare($date2)
{
if ($date2 != $this->input->post("date1"))
{
$this->form_validation->set_message('date_compare', 'Dates are different');
return FALSE;
}
else
{
return TRUE;
}
}
config:
'page2/send' => array(
array(
'field' => 'name',
'label' => 'lang:name',
'rules' => 'required'
),
array(
'field' => 'date1',
'label' => 'lang:date',
'rules' => 'required|'
)
array(
'field' => 'date2',
'label' => 'lang:date',
'rules' => 'required|callback_date_compare'
)
),
Upvotes: 0