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.

candidates.sql


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
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

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

ALTER TABLE `candidates`
  MODIFY `candidate_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1;

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:

application/views/register.php


<!DOCTYPE html>
<html lang="en">
<head>
  <title>Candidate Registration</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
  <link rel="stylesheet" href="<?php echo base_url('assets/css/style.css') ?>">
</head>
<body>
   <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">
            <label>Name</label>
            <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>
         <div class="form-group col-md-12">
            <label>Address</label>
            <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>
         <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>
         <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>
         <div class="col-md-12 text-center">
            <input type ="submit" name="submit" class="btn btn-primary" value="Submit">
         </div>
      </form>
   </div>
</body>
</html>

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.

application/controllers/CandidateController.php


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

class CandidateController extends CI_Controller {

	/**
	 * Index Page for this controller.
	 *
	 * Maps to the following URL
	 * 		http://example.com/index.php/welcome
	 *	- or -
	 * 		http://example.com/index.php/welcome/index
	 *	- or -
	 * Since this controller is set as the default controller in
	 * config/routes.php, it's displayed at http://example.com/
	 *
	 * So any other public methods not prefixed with an underscore will
	 * map to /index.php/welcome/
	 * @see  https://codeigniter.com/user_guide/general/urls.html
	 */
	function __construct() {
	    parent::__construct();
	    $this->load->model('ModelCandidate');
	}

	public function index(){
		$element = [];
		$element['succ_msg'] = "";
		$element['err_msg'] = "";
		$this->load->view('register',$element);
		}

	public function register(){
		$element = [];
		$element['succ_msg'] = "";
		$element['err_msg'] = "";
		// validate each field
		$this->form_validation->set_rules('name', 'Name', 'trim|required',
			array(
					'required'=>'You must provide a %s')
				);
		$this->form_validation->set_rules('addr', 'Address', 'trim|required',
			array(
				'required'=>'You must provide an %s')
			);
		$this->form_validation->set_rules('email', 'Email Id', 'trim|required|valid_email|is_unique[candidates.email_id]',
			array(
					'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',
			array(
					'required' => 'You must provide %s')
				);

		if ($this->form_validation->run() == FALSE) {
			// validation not passed, so load the form again
				$this->load->view('register',$element);
		} 
		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";
			}
			else{
				$element['err_msg'] = "Error in Registration";
			}
			$this->load->view('register',$element);
		}

	}  // 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;
		}
		else
			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;
		}
		else
			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:

application/models/ModelCandidate.php


class ModelCandidate extends CI_Model {

function __construct() {
  parent::__construct();
}

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

style.css


h4{
	text-align: center;
	margin-top: 50px;
}
p.success{
  text-align: center;
  color:green;
  font-size: 20px;
}
p.error{
  text-align: center;
  color:red;
  font-size: 20px;
}
.error{
  color:red;
  min-height: 20px;
  font-size: 17px;
}
label{
	font-weight: bold;
}
 #frm {
  margin: 5px auto;
  padding-top: 21px;
  padding-bottom: 40px;
  border: 1px solid #09168d;
  border-radius: 7px;
  background: #fff;
  width: 47%;
}
textarea.form-control{
	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.