Skip to content

Custom validation Rules in codeigniter ?

Last updated on January 31, 2021

CodeIgniter Form Validation Library is Pretty Simple to Use and very powerful. We can define our own Custom Validation Rules in CodeIgniter in two different approaches.

1. By Using Callbacks.
2. By Extend CodeIgniter’s Form Validation library.

Custom validation Rules Using Callbacks

custom validation in CodeIgniter using callback function is an easy way to validate form fields. Follow the Steps,

1. define your custom rule with callback_ prefix,

  $this->form_validation->set_rules('email_address', '"Email address"', 'trim|callback_email_check');

2. Then add the method in the controller. This method needs to return either TRUE or FALSE

function email_check($value)
{
  if($value) { // do your validations
     return TRUE;
   } else {
     return FALSE;
   }
}

3. The Final Step, create a corresponding error Message to show on validation fail

$this->form_validation->set_message('email_check','Email is not valid');

Custom validation Rules By Extend CodeIgniter’s Form Validation library

Create a new PHP’s Class file named MY_Form_validation.php and put it in the application/libraries/ directory, and extend it with CodeIgniter’s validation library.

CI =& get_instance();
	}
       function email_check($str) {           
         $this->CI->form_validation->set_message('email_check', 'The %s is not valid.');
         if($value) { // do your validations
                return TRUE;
          } else {
              return FALSE;
          }
       }
}

2. now add this to your validation rules

$this->form_validation->set_rules('email_address', '"Email address"', 'trim|email_check');
1 1 vote
Article Rating
Subscribe
Notify of
guest

9 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments