Custom form validation Codeigniter

There are 2 ways to implement custom form validation in codeigniter

1.) Create function in controller (in the same controller in which we are implementing the validation).
2.) Create own or custom library and create function in that file.

1.) Create function in same controller –

Create function and call it by using callback_.

Example – Here is an example how to validate Indian mobile number using custom form validation function –

public function _check_phone($phone)

{

  if(preg_match(‘/^(?:(?:\+|0{0,2})91(\s*[\ -]\s*)?|[0]?)?[789]\d{9}|(\d[ -]?){10}\d$/’,$phone))

{

return true;

} else {

$this->form_validation->set_message(‘_check_phone’, ‘%s ‘.$phone.’ is invalid format’);

return false;

}

}

Function Call –

$this->form_validation->set_rules(‘contact_no_1’, ‘Mobile Number’, ‘trim|required|xss_clean|min_length[10]|max_length[18]|callback__check_phone’);

Disadvantage – You can use that function only that controller. What will you do if you have to put the validation at multiple places (controllers) ? So, its better to create custom library and create function in that library.

2.) Create Custom Library –

Create custom library file(say my_form_validation) in application/libraries directory.

Example – Same Indian mobile number validation –

<?php 

/**

 * CIMembership

 * 

 * @package Libraries

 * @author 1stcoder Team

 * @copyright   Copyright (c) 2015 1stcoder. (http://www.1stcoder.com)

 * @license http://opensource.org/licenses/MIT MIT License

 */

defined(‘BASEPATH’) OR exit(‘No direct script access allowed’);

class MY_Form_validation extends CI_Form_validation 

{

protected $ci;

function __construct() {

parent::__construct();

$this->ci =& get_instance();

}

public function _check_phone($phone)

{

$this->ci->form_validation->set_message(‘_check_phone’, “This %s “.$phone.” is in invalid format!”);

  if(preg_match(‘/^(?:(?:\+|0{0,2})91(\s*[\ -]\s*)?|[0]?)?[789]\d{9}|(\d[ -]?){10}\d$/’,$phone))

{

return true;

} else {

return false;

}

}

}

Function Call –

 $this->load->library(‘my_form_validation’); //load the library

$this->form_validation->set_rules(‘contact_no_1’, ‘Mobile Number’, ‘trim|required|xss_clean|min_length[10]|max_length[18]|_check_phone’); // Call the functions like others

Note: You can create the function in both – controller and custom library But always prefer to write the function by creating custom library, so that in case, if need to use that function in multiple controllers, can be used easily.

 
 
 
____________________________________________
For more related queries, please visit.
In case, if you did not find your solution or have any query/question, please contact us.

Leave a Reply

Your email address will not be published. Required fields are marked *