Creating a custom codeigniter validation rule
You use the callback_
in your rules, see callbacks, for ex.
$this->form_validation->set_rules('email_address', '"Email address"', 'trim|required|valid_email|callback_validate_member');
and add the method in the controller. This method needs to return either TRUE or FALSE
function validate_member($str){ $field_value = $str; //this is redundant, but it's to show you how //the content of the fields gets automatically passed to the method if($this->members_model->validate_member($field_value)) { return TRUE; } else { return FALSE; }}
You then need to create a corresponding error in case the validation fails
$this->form_validation->set_message('validate_member','Member is not valid!');
One best way to achieve this is extending CodeIgniter’s Form Validation library. Let say we want to create a custom validator named access_code_unique
for the field access_code
of the database table users
.
All you have to do is creating a Class file named MY_Form_validation.php
in application/libraries
directory. The method should always return TRUE
OR FALSE
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');class MY_Form_validation extends CI_Form_validation { protected $CI; public function __construct() { parent::__construct(); // reference to the CodeIgniter super object $this->CI =& get_instance(); } public function access_code_unique($access_code, $table_name) { $this->CI->form_validation->set_message('access_code_unique', $this->CI->lang->line('access_code_invalid')); $where = array ( 'access_code' => $access_code ); $query = $this->CI->db->limit(1)->get_where($table_name, $where); return $query->num_rows() === 0; }}
Now you can easily add your new created rule
$this->form_validation->set_rules('access_code', $this->lang->line('access_code'), 'trim|xss_clean|access_code_unique[users]');