Custom form validation Codeigniter

There are 2 ways to do it –

1.) Create function in same controller.
2.) Create own or custom library and create function there.

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 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;

}

}

Calling –

$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 ?

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;

}

}

}

Calling –

 $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


Leave a Reply

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