How to Work with CodeIgniter 4 Form Validation Library

Share this Article
Reading Time: 10 minutes

Nowadays submitting a form with user input data is a common process. But do you think user always proceed with the valid input values?

If we think in real time application development then No, end users sure fill and do their experiment with form inputs with all possible ways.

Inside this article we will see CodeIgniter 4 Form Validation Library which is going to explain you about complete concept to learn and implement. Also we will see CodeIgniter 4 form validation by making a a simple form.

We will cover form validation rules available in CodeIgniter 4.

Note*: For this article, CodeIgniter v4.1 setup has been installed. May be when you are seeing, version will be updated. CodeIgniter 4.x still is in development mode.

Let’s get started.

Download & Install CodeIgniter 4 Setup

We need to download & install CodeIgniter 4 application setup to system.

To set application we have multiple options to proceed.

Here are the following ways to download and install CodeIgniter 4 –

  • Manual Download
  • Composer Installation
  • Clone Github repository of CodeIgniter 4

Complete introduction of CodeIgniter 4 basics – Click here to go. After going through this article you can easily download & install setup.

Here is the command to install via composer –

$ composer create-project codeigniter4/appstarter codeigniter-4

Assuming you have successfully installed application into your local system.

Now, let’s configure database and application connectivity.

Turn Development Mode On

When we install CodeIgniter 4, we have env file at root. To use the environment variables means using variables at global scope we need to do env to .env

Open project in terminal

$ cp env .env

Above command will create a copy of env file to .env file. Now we are ready to use environment variables.

CodeIgniter starts up in production mode by default. Let’s do it in development mode. So that while working if we get any error then error will show up.

# CI_ENVIRONMENT = production

 // Do it to 
CI_ENVIRONMENT = development

Now application is in development mode.

Create Database & Table in Application

We need to create a database. For database we will use MySQL. We have 2 options available to create database. Either we can use PhpMyAdmin Manual interface Or we can use command to create.

CREATE DATABASE codeigniter4_app;

Next, we need a table. That table will be responsible to store data. Let’s create table with some columns.

CREATE TABLE `tbl_members` (
 `name` varchar(120) DEFAULT NULL,
 `email` varchar(120) DEFAULT NULL,
 `mobile` varchar(45) DEFAULT NULL,

Successfully, we have created a database and a table. Let’s connect with the application.

Database Connectivity to Application

Open .env file from project root. Search for DATABASE. You should see the connection environment variables.

Let’s set the value for those to connect with database.

 database.default.hostname = localhost
 database.default.database = codeigniter4_app
 database.default.username = root
 database.default.password = root
 database.default.DBDriver = MySQLi

Now, database successfully connected with application.

Add Routes

Open Routes.php from /app/Config folder. Add this route into it.

//.. Other routes

$routes->match(["get", "post"], "add-member", "Member::addMember");

Let’s create Model.

Create Model

Open project into terminal and run this spark command to create model.

$ php spark make:model Member --suffix

It will create MemberModel.php at /app/Models folder. Opn MemberModel.php and write this complete code into it.


namespace App\Models;

use CodeIgniter\Model;

class MemberModel extends Model
	protected $DBGroup              = 'default';
	protected $table                = 'tbl_members';
	protected $primaryKey           = 'id';
	protected $useAutoIncrement     = true;
	protected $insertID             = 0;
	protected $returnType           = 'array';
	protected $useSoftDelete        = false;
	protected $protectFields        = true;
	protected $allowedFields        = [

	// Dates
	protected $useTimestamps        = false;
	protected $dateFormat           = 'datetime';
	protected $createdField         = 'created_at';
	protected $updatedField         = 'updated_at';
	protected $deletedField         = 'deleted_at';

	// Validation
	protected $validationRules      = [];
	protected $validationMessages   = [];
	protected $skipValidation       = false;
	protected $cleanValidationRules = true;

	// Callbacks
	protected $allowCallbacks       = true;
	protected $beforeInsert         = [];
	protected $afterInsert          = [];
	protected $beforeUpdate         = [];
	protected $afterUpdate          = [];
	protected $beforeFind           = [];
	protected $afterFind            = [];
	protected $beforeDelete         = [];
	protected $afterDelete          = [];

Model is pointing tbl_members table. We have specified all the table columns into $allowedFields. If suppose we don’t specify then it restrict that missing field from insertion.

Create Layout File

As, we have taken fields as name, email, mobile. So with respective with these fields we need to set the user layout.

Let’s create a view file add-member.php inside /app/Views folder. Open file and write this complete code into it.

  // To print success flash message
      <h3><?= session()->get("success") ?></h3>

  // To print error flash message
    <h3><?= session()->get("error") ?></h3>

  // To print error messages
    print_r($validation->listErrors() );


<form action="<?= site_url('add-member') ?>" method="post">
       Name: <input type="text" name="name" placeholder="Enter name"/>

       Email: <input type="email" name="email" placeholder="Enter email"/>

       Mobile: <input type="text" name="mobile" placeholder="Enter mobile"/>

     <button type="submit">Submit</button>
  • if(session()->get(“success”)){} – Checking for success key of temporary stored message.
  • session()->get(“success”) – Print session flash – success key message
  • if(session()->get(“error”)){} – Checking for success key of temporary stored message.
  • session()->get(“error”) – Print session flash – error key message
  • site_url(‘add-member’) – Site URL with add-member route
  • if(isset($validation)){} – Checking validation variable if it contains any error
  • print_r($validation->listErrors()); – Printing all error messages

Create Controller

Next we need to create application controllers.

Loading url Helper

Open BaseController.php from /app/Controllers folder. Search for $helpers, inside this helpers array simply add this url helper.

protected $helpers = [‘url’];

This url helper will load base_url() and site_url() functions.

Also we have the option to load any helper directly to any controller using helper() function.

Back to terminal and run this spark command.

$ php spark make:controller Member

It will create Member.php inside /app/Controllers folder. Open Member.php and write this complete code into it.


namespace App\Controllers;

use App\Models\MemberModel;

class Member extends BaseController
    public function addMember()
        if ($this->request->getMethod() == "post") {

            $memberModel = new MemberModel();

            $rules = [
                "name" => "required|min_length[3]|max_length[255]",
                "email" => "required",
                "mobile" => "required",

            // If we want to use custom messages for errors
            // otherwise by default system will take care automatically
            $messages = [
                "name" => [
                    "required" => "Name is required",
                    "min_length" => "Minimum length of Name should be 3",
                    "max_length" => "Maximum length of Name is 255 chars",
                "email" => [
                    "required" => "Email is required",
                "mobile" => [
                    "required" => "Mobile Number is required",
           $session = session(); // loading session service

            if (!$this->validate($rules, $messages)) {

                return view("add-member", [
                    "validation" => $this->validator,
            } else {

                $data = [
                    "name" => $this->request->getVar("name"),
                    "email" => $this->request->getVar("email"),
                    "mobile" => $this->request->getVar("mobile"),

                if ($memberModel->insert($data)) {

                    $session->setFlashdata("success", "Data saved successfully");
                } else {

                    $session->setFlashdata("error", "Failed to save data");

                return redirect()->to(base_url());
        return view("add-member");

All available form validation rules for input fields Click here to go.

  • if ($this->request->getMethod() == “post”) {} – Checking request method type. Same method we are using for GET and POST.
  • $memberModel = new MemberModel(); – Creating Model instance
  • $rules = [] – Defining rules for input fields
  • $messages = [] – Defining error message (user defined)
  • if (!$this->validate($rules, $messages)) {} – Validating input field with rules and messages. It returns false when input fields not satisfies the defined rules of $rules = []; If it satisfies all conditions then return true value.
  • “validation” => $this->validator – Validator returns the form validation error message, we are simply assigning to validation key.
  • $this->request->getVar(“name”) – Reading value of input field with “name” attribute.
  • if ($memberModel->insert($data)) {} – Saving data to table and returning it’s status after save.
  • $session->setFlashdata(“success”, “Data saved successfully”);
  • return redirect()->to(base_url()); – Redirecting to application base url after all operation.

To Check any input field has any error or not

     Name : <input type="text" name="name" class="<?= ($validation->hasError('name')) ? 'is-error' : '' ?>"/>  

Here, inside above code we are checking the field error, it exists then we are adding a class into input field with the name of is-error.

Print any specific field error

if ($validation->hasError('name')){
    echo $validation->getError('name');

Application Testing

Start development server:

$ php spark serve

Open application into browser.

URL – http://localhost:8080/add-member

Form View –

Form with Validation

We hope this article helped you to learn about CodeIgniter 4 Form Validation Library in a very detailed way.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.

Find More on CodeIgniter 4 here