[eluser]Unknown[/eluser]
Hey,
I've been using CodeIgniter for a couple of days now as framework of a rather large application interacting with a couple of VoIP servers. So far it's been great.
However, I found one limitation in the form validation class. I like to filter a value of a selectbox against a whitelist array.
In its simplest form:
Code:
<?php
$white_list = array(1, 2, 3);
$post_result = $_POST['my_selectbox'];
if(!in_array($post_result, $white_list) die('No access here!');
?>
I discovered the Form_validation library has no such feature, so I decided to create one myself, which I would like to share with you all. Perhaps there's a better solution which one of you would want to share with me, instead?
First of all, I created a file in system/application/libraries called
My_Form_validation.php:
Code:
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
/**
* My Validation class
*
* Adds a couple of validation rules, such as an in_array() check
*/
class My_Form_validation extends CI_Form_validation
{
/**
* Constructor
*
* @return void
*/
function My_Form_validation()
{
parent::CI_Form_validation();
}
/**
* Apparantly, when writing a validation rule, it won't accept an array as param
*
* i.e. $this->form_validation->set_rules('servers', 'servers', 'is_in_array['.$array.']');
*
* $array can't be an array... that's why we convert our array to a string first, using implode
*
* The 2nd parameter allows you to choose between array keys or just values
*
* @param array
* @param bool
* @return string
*/
function prepare_array($array, $keys = true)
{
// We need to create a string out of this array
if(is_array($array) && count($array))
{
if($keys)
{
$array = array_keys($array);
}
$string = implode(',', $array);
}
return $string;
}
/**
* Basically the in_array() php function, but then wrapped in the CI_Validation class
*
* We receive a comma seperated string (imploded), which we will need to explode again
*
* @param mixed
* @param string
* @return bool
*/
function is_in_array($val = '', $array = '')
{
$array = explode(',', $array);
return in_array($val, $array);
}
}
/* End of file Isaeus_Form_validation.php */
/* Location: ./system/application/libraries/Isaeus_Form_validation.php */
Basically, the comments should say it all. When using:
Code:
$this->form_validation->set_rules('servers', 'servers', 'is_in_array['.$white_list.']');
$white_list can't be an array. That's why I created a function that will turn it into a comma seperated string, which should be called like this:
Code:
$white_list = $this->form_validation->prepare_array($servers);
Setting the 2nd parameter to false (default is true), $white_list will contain the array of just the values, so you don't need two seperate functions (in_array() and array_key_exists()).
Now I'll just need to think of a workaround for whenever a value might contain a comma, cause that will obviously mess things up. Ideally, I should make the delimiter configurable. Feel free to add to this.