How to do form validation in CodeIgniter 3

If you are developing a form for the user, you must write the form validation code to allow only the valid data to be stored in the database. In this topic, we will create a simple registration form in CodeIgniter 3 as an example. Our main purpose is to know how to validate the form in CodeIgniter 3. Form validation will be performed after the form is submitted and before data is inserted into the database table.

Create a MySQL table for candidate details

Let us create the table named 'candidates' in MySQL database. Table structure is given below:

Table: candidates

This table stores details of all registered candidates.

CodeIgniter Form Validation with Form Submit Example

Below are the columns in this table.

  1. candidate_id - It is the primary key and auto incremented id of the candidate
  2. name - Name of the candidate
  3. address - Address of the candidate
  4. email_id - Email Id of the candidate
  5. age - Age of the candidate
Create table script for this table is given below.


CREATE TABLE `candidates` (
  `candidate_id` int(11) NOT NULL,
  `name` varchar(100) NOT NULL,
  `address` varchar(200) NOT NULL,
  `email_id` varchar(100) NOT NULL,
  `age` smallint(6) NOT NULL

ALTER TABLE `candidates`
  ADD PRIMARY KEY (`candidate_id`);

ALTER TABLE `candidates`

After you create the table, verify if the table structure is the same as above.

Create the view for registration form (register.php)

It is a simple registration form with input fields name, address, email id and age. There will be validation for each field. For age, we will be using a range (18-40) so that we can show how this type of validation can be done in CodeIgniter 3. Let us see the form below:


<!DOCTYPE html>
<html lang="en">
  <title>Candidate Registration</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="">
  <link rel="stylesheet" href="<?php echo base_url('assets/css/style.css') ?>">
   <div class="container">
      <h4>Candidate Registration</h4>
      <p class="error "><?php if ($err_msg != "") { echo $err_msg;}?></p>
      <p class="success"><?php if ($succ_msg !="") {echo $succ_msg;}?></p>
      <form id ="frm" action = "<?php echo base_url()?>register" method = "post">
         <div class="form-group col-md-12">
            <input type = "text" name="name" id = "name" class="form-control" value="<?php echo set_value('name');?>" maxlength="100" placeholder="Enter Your Name">
            <div class="error"><?php echo form_error('name'); ?></div>
         <div class="form-group col-md-12">
            <textarea name="addr" id = "addr" class="form-control" maxlength="200" placeholder="Enter Your Address" ><?php echo set_value('addr');?></textarea>
            <div class="error"><?php echo form_error('addr'); ?></div>
         <div class="form-group col-md-12">
            <label>Email Id</label>
            <input type = "text" name="email" id = "email" class="form-control"  value="<?php echo set_value('email');?>" maxlength="100" placeholder="Enter Your Email">
            <div class="error"><?php echo form_error('email'); ?></div>
         <div class="form-group col-md-12">
            <label>Age <small>(Must be between 18 and 40 only)</small></label>
            <input type = "number" name="age" id = "age" class="form-control" value="<?php echo set_value('age');?>" placeholder="Enter Your Age in Years">
            <div class="error"><?php echo form_error('age'); ?></div>
         <div class="col-md-12 text-center">
            <input type ="submit" name="submit" class="btn btn-primary" value="Submit">

It is a form with a few input fields and a submit button. Note that for each input field set_value() will repopulate the value in case of validation error for the field. Also, for each input field, a validation error message is displayed using form_error().

Write Controller with validation rules (CandidateController.php)

Our controller will have an index() method to display the form and a register() method to process the submitted form. register() method is the one where form validation will take place. We will have an additional method for the age validation callback function. Let's see the code below for the controller class.


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

class CandidateController extends CI_Controller {

	 * Index Page for this controller.
	 * Maps to the following URL
	 *	- or -
	 *	- or -
	 * Since this controller is set as the default controller in
	 * config/routes.php, it's displayed at
	 * So any other public methods not prefixed with an underscore will
	 * map to /index.php/welcome/
	 * @see
	function __construct() {

	public function index(){
		$element = [];
		$element['succ_msg'] = "";
		$element['err_msg'] = "";

	public function register(){
		$element = [];
		$element['succ_msg'] = "";
		$element['err_msg'] = "";
		// validate each field
		$this->form_validation->set_rules('name', 'Name', 'trim|required',
					'required'=>'You must provide a %s')
		$this->form_validation->set_rules('addr', 'Address', 'trim|required',
				'required'=>'You must provide an %s')
		$this->form_validation->set_rules('email', 'Email Id', 'trim|required|valid_email|is_unique[candidates.email_id]',
					'required'=>'You must provide an %s',
					'valid_email' => 'This is not a valid email address',
					'is_unique' => 'This %s already exists')
		$this->form_validation->set_rules('age', 'Age', 'trim|required|callback_age_check',
					'required' => 'You must provide %s')

		if ($this->form_validation->run() == FALSE) {
			// validation not passed, so load the form again
		else {
			// validation is success, so go for registration
			// get the values of form fields
			$name = $this->input->post('name');
			$addr = $this->input->post('addr');
			$email = $this->input->post('email');
			$age = $this->input->post('age');
			$data = array('name'=>$name, 'address'=>$addr, 'email_id'=>$email, 'age'=>$age);
			$result = $this->ModelCandidate->register($data);
			if ($result){
				$element['succ_msg'] = "Registration successful";
				$element['err_msg'] = "Error in Registration";

	}  // end of register method 

public function age_check($age){
	if (!empty($age)){
		if ($age <18 || $age >40) {
			$this->form_validation->set_message('age_check', '{field} must be between 18 and 40');
			return false;
			return true;

} // end of controller class

In the constructor, we are loading the model named 'ModelCandidate'.

Controller Method index()

index() method is executed by default in a controller. In this method, it just loads the view that displays the registration form.

Controller Method register()

This method gets executed after form submission. It writes validation rules for each field. If validation fails for a field, it reloads the view with an error message displayed for the field. But if all fields are validated successfully, this method calls a Model method to insert a row in the database.

It uses form_validation->set_rules() method for each field. Validation for the Age field is done using a custom callback method named age_check() which is defined later in the controller. This callback method returns TRUE or FALSE. Let's see the callback method age_check() below:

public function age_check($age){
	if (!empty($age)){
		if ($age <18 || $age >40) {
			$this->form_validation->set_message('age_check', '{field} must be between 18 and 40');
			return false;
			return true;

It takes the value of the field as a parameter and checks if the value is less than 18 or greater than 40. If the value is outside this range, it sets a message and returns FALSE. Otherwise, it returns TRUE.

The Model (ModelCandidate.php)

In the model, register() method takes the input array and uses $db->insert() to insert a row in the database table. Below is the model code:


class ModelCandidate extends CI_Model {

function __construct() {

function register($data = []) {
  if (!empty($data)) {
    $result = $this->db->insert('candidates', $data);
    return $result;


	text-align: center;
	margin-top: 50px;
  text-align: center;
  font-size: 20px;
  text-align: center;
  font-size: 20px;
  min-height: 20px;
  font-size: 17px;
	font-weight: bold;
 #frm {
  margin: 5px auto;
  padding-top: 21px;
  padding-bottom: 40px;
  border: 1px solid #09168d;
  border-radius: 7px;
  background: #fff;
  width: 47%;
	resize: none !important;
	height: 100px !important;

We added a few simple styles here, you can always add better styles.

Update Configuration files and Test the Application

Let us now update a few setup files before we run the application. The project folder name is 'registration' under xampp/htdocs. So, the root directory is xampp/htdocs/registration.

Create registration form in CodeIgniter

The folder 'assets' is created to keep all stylesheets, JavaScripts and image files.

We will update few files in config folder and also write .htaccess file under the root. See below:

  1. Update autoload.php (application/config/autoload.php)

    We added 'database' and 'form_validation' in autoload libraries.

    $autoload['libraries'] = array('database','session','form_validation');

    Also, 'url' and 'form' are added in helper array.

    $autoload['helper'] = array('url','form');
  2. Update config file (application/config/config.php)
    $config['base_url'] = 'http://localhost/registration/';
    $config['index_page'] = '';
  3. Update database setup file (application/config/database.php)
    $active_group = 'default';
    $query_builder = TRUE;
    $db['default'] = array(
    	'dsn'	=> '',
    	'hostname' => 'localhost',
    	'username' => 'root',
    	'password' => '',
    	'database' => 'demo',
    	'dbdriver' => 'mysqli',
    	'dbprefix' => '',
    	'pconnect' => FALSE,
    	'db_debug' => (ENVIRONMENT !== 'production'),
    	'cache_on' => FALSE,
    	'cachedir' => '',
    	'char_set' => 'utf8',
    	'dbcollat' => 'utf8_general_ci',
    	'swap_pre' => '',
    	'encrypt' => FALSE,
    	'compress' => FALSE,
    	'stricton' => FALSE,
    	'failover' => array(),
    	'save_queries' => TRUE
  4. Update routes file (application/config/routes.php) Update routes.php for default controller which is CandidateController:
    $route['default_controller'] = 'CandidateController';
    $route['register'] = 'CandidateController/register';
    $route['404_override'] = '';
    $route['translate_uri_dashes'] = FALSE;
  5. Update .htaccess (hypertext access) file to remove index.php from the URL
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.php?/$1 [L]

Test The Application

Run localhost/registration in the browser. You will see the registration form displayed as below:

codeigniter form validation example

You can test the validation and successful registration. Just try to submit an incomplete form and see the error messages. Do not forget to test age validation.

When you enter all valid values and submit the form, registration should be completed successfully and you can check with the database table if the row is inserted into it.

How to validate a form in CodeIgniter 3Conclusion

Form validation is an important part of any project. Using an example, we created a form and used the CodeIgniter form validation rules. We also used a custom validation. I hope this will be useful to you.