Form Inputs Validation by Model CodeIgniter 4 Tutorial

Share this Article

Validation is one of the basic settings which always should do with forms. Form validation using Model. Already we have several articles over Validation rules in CodeIgniter 4. Click here To learn Form Validation Library. Inside this article, we will see the concept of Form inputs validation by model.

We will see this concept step by step. It will be very interesting topic to see and learn.

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.


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_form;

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 application root.

#--------------------------------------------------------------------
# DATABASE
#--------------------------------------------------------------------
 database.default.hostname = localhost
 database.default.database = codeigniter4_form
 database.default.username = root
 database.default.password = root
 database.default.DBDriver = MySQLi
   

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", "MemberController::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
<?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.

Inside this model skeleton, protected $validationRules, protected $validationMessages these are the variables used for providing input validations.

// Validation
protected $validationRules = [
   "name" => "required|min_length[3]|max_length[120]",
   "email" => "required|valid_email|min_length[5]|is_unique[tbl_members.email]",
   "mobile" => "required"
];

protected $validationMessages = [
  "name" => [
     "required" => "Name is required",   
     "min_length" => "Minimum length of name should be 3 chars",
     "max_length" => "Maximum length of name should be 120 chars",
   ],
   "email" => [
      "required" => "Email needed",
      "valid_email" => "Please provide a valid email address"
   ],
  "mobile" => [
      "required" => "Mobile number needed"
   ]
];

Here, we have written form input validation rules and messages.

Updated MemberModel.php

<?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      = [
		"name" => "required|min_length[3]|max_length[120]",
		"email" => "required|valid_email|min_length[5]|is_unique[tbl_members.email]",
		"mobile" => "required"
	];
	protected $validationMessages   = [
		"name" => [
			"required" => "Name is required",
			"min_length" => "Minimum length of name should be 3 chars",
			"max_length" => "Maximum length of name should be 120 chars",
		],
		"email" => [
			"required" => "Email needed",
			"valid_email" => "Please provide a valid email address"
		],
		"mobile" => [
			"required" => "Mobile number needed"
		]
	];
	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          = [];
}

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

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>

<div class="container" style="margin-top:50px;">
    <div class="panel panel-primary">
        <div class="panel-heading">Form</div>
        <div class="panel-body">

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

            <?php
            // To print error messages
            if (!empty($errors)) : ?>
                <div class="alert alert-danger">
                    <?php foreach ($errors as $field => $error) : ?>
                        <p><?= $error ?></p>
                    <?php endforeach ?>
                </div>
            <?php endif ?>

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

                <p>
                    Email: <input type="email" class="form-control" name="email" placeholder="Enter email" />
                </p>

                <p>
                    Mobile: <input type="text" class="form-control" name="mobile" placeholder="Enter mobile" />
                </p>

                <p>
                    <button type="submit" class="btn btn-success">Submit</button>
                </p>
            </form>
        </div>
    </div>
</div>

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 MemberController.php inside the given folder.

$ php spark make:controller Member --suffix

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

<?php

namespace App\Controllers;

use App\Models\MemberModel;

class MemberController extends BaseController
{
	public function addMember()
	{
		helper(["url"]);

		if ($this->request->getMethod() == "post") {

			$memberModel = new MemberModel();

			$session = session(); // loading session service

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

			if ($memberModel->save($data) === false) {

				return view('add-member', [
					'errors' => $memberModel->errors()
				]);
			} else {

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

				return redirect()->to(base_url('add-member'));
			}
		}
		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
  • $memberModel->save($data) === false – Validating input field with rules and messages.
  • “errors”, $memberModel->errors() Storing errors into errors variable.
  • $this->request->getVar(“name”) – Reading value of input field with “name” attribute.
  • $session->setFlashdata(“success”, “Data saved successfully”);
  • return redirect()->to(base_url(‘add-member’)); – Redirecting to add-member route after operation.

Another Way to Bind validations with Model

If we follow this, no need to add rules and messages into Model file. We can also control input validation from here.

public function addMember()
{
  helper(["url"]);

  if ($this->request->getMethod() == "post") {

    $memberModel = new MemberModel();

    $session = session(); // loading session service

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

    $validationRules = [
      "name" => "required|min_length[3]|max_length[120]",
      "email" => "required|valid_email|min_length[5]|is_unique[tbl_members.email]",
      "mobile" => "required"
    ];
    $memberModel->setValidationRules($validationRules);

    $fieldValidationMessage = [
      "name" => [
        "required" => "Name is required",
        "min_length" => "Minimum length of name should be 3 chars",
        "max_length" => "Maximum length of name should be 120 chars",
      ],
      "email" => [
        "required" => "Email needed",
        "valid_email" => "Please provide a valid email address"
      ],
      "mobile" => [
        "required" => "Mobile number needed"
      ]
    ];
    $memberModel->setValidationMessages($fieldValidationMessage);

    if ($memberModel->save($data) === false) {

      return view('add-member', [
        'errors' => $memberModel->errors()
      ]);
    } else {

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

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

Application Testing

Start development server:

$ php spark serve

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

Submitting Form without any inputs

Submitting form with Inputs

We hope this article helped you to learn about Form Inputs Validation by Model CodeIgniter 4 Tutorial 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