How to Work with CodeIgniter 4 Form Validation Library

Share this Article
Reading Time: 10 minutes
6,050 Views

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.

Learn More –

Let’s get started.


CodeIgniter 4 Installation

To create a CodeIgniter 4 setup run this given command into your shell or terminal. Please make sure composer should be installed.

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


.env Setup

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

Either we can do via renaming file as simple as that. Also we can do by terminal command.

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.

Enable Development Mode

CodeIgniter starts up in production mode by default. You need to make it in development mode to see any error if you are working with application.

Open .env file from root.

# CI_ENVIRONMENT = production

 // Do it to 
 
CI_ENVIRONMENT = development

Now application is in development mode.


Create Database

To create a database, either we can create via Manual tool of PhpMyadmin or by means of a mysql command.

CREATE DATABASE codeigniter4_app;

Successfully, we have created a database.


Create Database Table

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 table. Let’s connect with the application.


Database Connection

Open .env file from project root.

Search for DATABASE. You should see the connection environment variables. Give your updated details of database connection string.

 
#--------------------------------------------------------------------
# DATABASE
#--------------------------------------------------------------------

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

Now, database successfully connected with the application.


Add Routes

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

//...

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

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


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.

<?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

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.

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

//...

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.

Buy Me a Coffee

Online Web Tutor invites you to try Skillshare free for 1 month! Learn CakePHP 4, Laravel APIs Development, CodeIgniter 4, Node Js, etc into a depth level. Master the Coding Skills to Become an Expert in Web Development. So, Search your favourite course and enroll now. Click here to join.

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.

Was this post helpful?

Learn Web Development Courses Risk Free @ $5 only.
Web Development Courses @ $5