CodeIgniter 4 Form Validation Tutorial with Example

Last Updated on by in CodeIgniter
This tutorial explains how to create a form using Bootstrap and form validation in Codeigniter 4 application. There are two types of validation client-side and server-side.We will focus on server-side validation and use Codeigniter’s built-in validation rules to validate a form from scratch.

Codeigniter 4 Form Validation Tutorial

Install / Download Codeigniter 4

There are two ways through which you can make Codeigniter up and running. We are going to look at both the outlooks.

For this step, you must have a composer package installed on your development machine. Execute the below command to install the Codeigniter application with the composer.

composer create-project codeigniter4/appstarter

After installation change the application folder name. I have named it codeigniter-form-validation. Then, get inside the project folder.

cd codeigniter-form-validation

This is the simple and straightforward method. Just click on the following link to easily Download the Codeigniter 4 application.

Show Errors in Codeigniter

To easily debug the application, we will enable the error reporting in our Codeigniter app.

Open app/Config/Boot/development.php file and set the display_errors to 1 instead of 0. Do the same thing in app/Config/Boot/production.php file.

ini_set('display_errors', '1');

Make Database Connection

Add your database name, username and password in application/config/database.php and create the coherence between Database and Codeigniter.

public $default = [
        'DSN'      => '',
        'hostname' => 'localhost',
        'username' => 'root',
        'password' => 'root',
        'database' => 'demo',
        'DBDriver' => 'MySQLi',
        'DBPrefix' => '',
        'pConnect' => false,
        'DBDebug'  => (ENVIRONMENT !== 'development'),
        'cacheOn'  => false,
        'cacheDir' => '',
        'charset'  => 'utf8',
        'DBCollat' => 'utf8_general_ci',
        'swapPre'  => '',
        'encrypt'  => false,
        'compress' => false,
        'strictOn' => false,
        'failover' => [],
        'port'     => 3306,

Run the SQL query from PHPMyAdmin to generate users table and along with insert some fake data.

CREATE TABLE `users` (
  `id` int(11) NOT NULL,
  `name` varchar(255) NOT NULL,
  `email` varchar(50) NOT NULL,
  `phone` varchar(20) NOT NULL

CodeIgniter\Database\Exceptions\DatabaseException #8
Unable to connect database : Codeigniter

If anyhow you get the Codeigniter – cannot connect to MySQL database error, then change the hostname value based on your local server e.g MAMPP or XAMPP.

public $default = [
     'hostname' => '/Applications/MAMP/tmp/mysql/mysql.sock',

public $default = [
     'hostname' => '/Applications/XAMPP/xamppfiles/var/mysql/mysql.sock',

Create New Model

Create app/Models/FormModel.php file in the Models folder, afterwards place the following code.

namespace App\Models;
use CodeIgniter\Model;

class FormModel extends Model
    protected $table = 'users';
    protected $primaryKey = 'id';
    protected $allowedFields = ['name', 'email', 'phone'];

You can play around with various other configuration options to handle Models in Codeigniter.

Create Controller

Now, to handle form validation, we have to create the two essential functions.

The index() function renders the contact form template into the view.

The contactForm() method handles the form of validation and contains various variables. The helper() method manifests autoload helper array.

Create the app/Controllers/FormController.php file and add the given below code in it.

namespace App\Controllers;
use App\Models\FormModel;
use CodeIgniter\Controller;

class FormController extends Controller

    public function index() {
        $data = [];
        return view('contact_form');
    public function store() {
        $rules = [
            'name' => 'required|min_length[3]',
            'email' => 'required|valid_email',
            'phone' => 'required|numeric|max_length[10]'
            $formModel = new FormModel();

            $data = [
                'name' => $this->request->getVar('name'),
                'email'  => $this->request->getVar('email'),
                'phone'  => $this->request->getVar('phone'),


            return redirect()->to('/contact-form');
            $data['validation'] = $this->validator;
            echo view('contact_form', $data);


We have added required, min length, max length, valid email, and numeric values validation. However, there are tons of validation options that give impetus to form validation in Codeigniter.

Create Routes

We have to define a route, it will be displaying the contact form and submitting the data in the database on successful form submission. To generate the route insert the following code in the app/Config/Routes.php file.

$routes->get('contact-form', 'FormController::index');
$routes->match(['get', 'post'], 'FormController/store', 'FormController::store');

Create Form & Show Server Side Errors

Next, let’s create a form with Bootstrap UI framework. We will display server-side errors for every element in the contact form template.

Open app/Views/contact_form.php file and place the following code inside of it.

<!doctype html>
<html lang="en">

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <title>Codeigniter 4 Form Validation Example -</title>
  <link rel="stylesheet" href="">
    .container {
      max-width: 550px;

  <div class="container mt-5">
    <?php $validation = \Config\Services::validation(); ?>

    <form action="<?php echo base_url(); ?>/FormController/store" method="post">
      <div class="form-group">
        <input type="text" name="name" class="form-control">

        <!-- Error -->
        <?php if($validation->getError('name')) {?>
            <div class='alert alert-danger mt-2'>
              <?= $error = $validation->getError('name'); ?>
        <?php }?>

      <div class="form-group">
        <input type="text" name="email" class="form-control">

        <!-- Error -->
        <?php if($validation->getError('email')) {?>
            <div class='alert alert-danger mt-2'>
              <?= $error = $validation->getError('email'); ?>
        <?php }?>

      <div class="form-group">
        <input type="text" name="phone" class="form-control">

        <!-- Error -->
        <?php if($validation->getError('phone')) {?>
            <div class='alert alert-danger mt-2'>
              <?= $error = $validation->getError('phone'); ?>
        <?php }?>

      <div class="form-group">
        <button type="submit" class="btn btn-primary btn-block">Submit</button>



Start the Application

Run the command to start the application:

php spark serve

Enter the following URL in the browser to view the form and form validation:



Eventually, we have completed the Codeigniter Form Validation tutorial with an example. In this tutorial, we have seen how to implement necessary form validation in the Codeigniter application from scratch.

We have gone through every foundational step, and i assume you must have understood every topic gradually.

The entire memoir will surely help us to develop our programming skills in Codeigniter web development. The assortment of every step has been put up in the right place.

I have shared my outlook with you, anyhow you find the lackness of coherence in this tutorial, due to my recklessness, do let me know. I will surely resolve it for you.

You can download the full code of this tutorial from GitHub.

Digamber - Author

Hi, I'm Digamber Singh, a New Delhi-based full-stack developer, tech author, and open-source contributor with 10+ years' experience in HTML, CSS, JavaScript, PHP, and WordPress.