Two new CI Form Validation features

Just checking out CI 2.1.0 last night, and noticed they have added two small but really useful features to the Form Validation libraries that will save you a bit of time if you know about.


Ah, finally - no more callbacks to check if the username or email has been taken! With 3 simple lines of code, that headache is code forever.

From the system/libraries/Form_validation.php, line: 951:

public function is_unique($str, $field)


list($table, $field)=explode('.', $field);

$query = $this->CI->db->limit(1)->get_where($table, array($field => $str));

return $query->num_rows() === 0;


So, simply add a validation rule such as

$this->form_validation->set_rules('email', 'Email', 'required|is_unique[]');

and you are done!

Passing params to callbacks

Callback functions can now recieve a parameter!

Extending the userguide's example,

$this->form_validation->set_rules('username', 'Username', 'required|callback_username_check[6]');

will now pass the parameter as the second argument:

public function username_check($str, $var)


if ($str == 'test' && $var < 5)


$this->form_validation->set_message('username_check', 'The %s field can not be the word "test"');

return FALSE;




return TRUE;



Note that passing a string requires "my string", with quotes inside the brackets (I thought the example code wasn't as clear on that as it might have been). Passing a variable should look like:

$this->form_validation->set_rules('username', 'Username', 'required|callback_username_check['.$var.']');

Unfortunately,  this can only be a string (or something implicitly convertible to a string) - arrays and objects are not yet supported.


Contact me