CodeIgniter 4 Form Validation Library

Share this Article

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.


Settings Environment Variables

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` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `name` varchar(120) DEFAULT NULL,
 `email` varchar(120) DEFAULT NULL,
 `mobile` varchar(45) DEFAULT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

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
#-------------------------------------------------------------------- 
 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.


Application Route Configuration

To configure application routes, we need to open up the file /app/Config/Routes.php. This is the main routes config file where we will put all routes of application. So for now we will a route which is used for both GET and POST request type.

//.. Other routes

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

Here, we have configured our application.

Let’s create Model.


Create Application Model

Model is the face of application with the database. We need a Member Model which will do some basic model configuration.

Models are created at /app/Models. We are going to create MemberModel.php at this location.

$ php spark make:model Member --suffix

It will create MemberModel.php at /app/Models folder.

<?php

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        = [
		"name", 
		"email", 
		"mobile"
	];

	// 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.


View File – Create User Form

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 /app/Views/add-member.php

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

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

  // To print error messages
  if(isset($validation)){
    
    print_r($validation->listErrors() );
  }

?>

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

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

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

   <p>
     <button type="submit">Submit</button>
   </p>
</form>
  • 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

Application Controller Settings

Controller is the functional file. Firstly let’s load some helpers at Parent Controller i.e BaseController.php. This file is in /app/Controllers folder.

Search helpers in BaseController and load “url” into helpers.

protected $helpers = [‘url’];

After loading this url helper, we will able to use site_url() and base_url() in Controllers & Views else we should have some error. Or if suppose, we don’t want to define helper in BaseController.php then also you can define at each specific controller file.

At Controller – helper([“url”]);

We will create application controller at /app/Controllers. Let’s create Member.php inside the given folder.

$ php spark make:controller Member

Write the following code into /app/Controllers/Member.php

<?php

namespace App\Controllers;

use App\Models\MemberModel;

class Member extends BaseController
{
    public function addMember()
    {
        helper(["url"]);  
       
        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

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

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');
}

Testing Application

Open project into terminal and start development server.

$ php spark serve

Open application into browser.

Application 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

Leave a Comment