Reputation: 51
I want to create custom validation rule in CodeIgniter 3 but I want to validate posted array (not a string). In CodeIgniter docs, I saw array are also supported.
HTML:
<select name="bonus[]" class="form-control"> ... </select>
<select name="bonus[]" class="form-control"> ... </select>
<select name="bonus[]" class="form-control"> ... </select>
VALIDATION:
$this->form_validation->set_rules("bonus[]", "Bonuses", "all_unique");
VALIDATION RULE all_unique
public function all_unique($array)
{
$this->CI->form_validation->set_message('all_unique', '%s are not unique.');
if(count(array_unique($array))<count($array))
{
// Array has duplicates
return FALSE;
}
else
{
// Array does not have duplicates
return TRUE;
}
}
In general I want to check if selected bonuses are not duplicate. (Number of select bonus fields can vary.)
The problem with this is the value passed to all_unique validation method is passed as a string not as an array, it is the value of the first bonus[] field. How can I validate array of send bonus[].
Upvotes: 1
Views: 1437
Reputation: 22532
You need to use callback
in set_message
to call all_unique
function
$this->form_validation->set_rules("bonus[]", "Bonuses", "callback_all_unique");
To get array field value inside call back use post method as
function all_unique()
{
$array = $this->input->post('bonus');// get bonus value
$this->CI->form_validation->set_message('all_unique', '%s are not unique.');
if(count(array_unique($array))<count($array))
{
// Array has duplicates
return FALSE;
}
else
{
// Array does not have duplicates
return TRUE;
}
}
Upvotes: 1