Form Validation in Codeigniter
In codeigniter we can easily apply custom validation to form. There is a simple process to apply custom form validation in codeigniter. we can apply custom validation using rules or using library.
Create a file named as MY_Form_validation.php in your CodeIgniter/application/Libraries folder.
<?php if ( ! defined(‘BASEPATH’)) exit(‘No direct script access allowed’);
class MY_Form_validation extends CI_Form_validation {
protected $CI;
function __construct()
{
parent::__construct();
$this->CI =& get_instance();
}
}
In you Controller file named as register.php as below,
<?php
class Register extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->helper(‘url’);
}
function index()
{
$this->load->view(‘viewfolder /register.php’);
}
function insert()
{
$this->load->helper(array(‘form’, ‘url’));
$this->load->library(‘form_validation’);
$this->form_validation->set_rules(‘name’, ‘name’, ‘required’);
$this->form_validation->set_rules(‘address’, ‘address’, ‘required’);
$this->form_validation->set_rules(‘phone_number’, ‘phone_number’, ‘required’);
$this->form_validation->set_rules(‘username’, ‘username’, ‘required’);
$this->form_validation->set_rules(‘password’, ‘Password’, ‘trim|required|min_length[5]|matches[password]|md5’);
if ($this->form_validation->run() == FALSE)
{
$this->load->view(‘viewfolder/register.php’);
}
else
{
$this->load->model(‘register_model’);
$this->register_model->insert();
$this->load->view(‘viewfolder /success.php’);
}
}
}
?>
In your inside the body create this,
<?php
$this->form_validation->set_message(‘rule’,’Error Message’);
?>
In your view file contain,
<form action=”<?php echo $this->config->base_url();?>Register/insert” method=”post”> Name <input type = “text” name=”name” style=”width: 240px; font-size: 13px”><?php echo form_error(‘name’, ‘<div class=”error”>’, ‘</div>’); ?><br>
Address <textarea name=”address” style=”width: 240px; font-size: 13px”></textarea><?php echo form_error(‘address’, ‘<div class=”error”>’, ‘</div>’); ?><br>
Phone Number<br/> <input type =”text” name=”phone_number” style=”width: 240px; font-size: 13px”><?php echo form_error(‘phone_number’, ‘<div class=”error”>’, ‘</div>’); ?><br>
Username <input type =”text” name=”username”style=”width: 240px; font-size: 13px” ><?php echo form_error(‘username’, ‘<div class=”error”>’, ‘</div>’); ?><br>
Password <input type =”password” name=”password” style=”width: 240px; font-size: 13px”><?php echo form_error(‘password’, ‘<div class=”error”>’, ‘</div>’); ?><br><input type=”submit” value=”Register”> </form>