Form Inputs Validation by Model CodeIgniter 4 Tutorial

Share this Article
Reading Time: 11 minutes
3,923 Views

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.

Learn More –

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.


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


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 Route

Open Routes.php from /app/Config. Add this route.

//...

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

//...

Here, we have configured our application.

Let’s create Model.


Create 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 to 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          = [];
}

Create View Layout

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.

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Form Inputs Validation by Model CodeIgniter 4 Tutorial</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <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>
</head>
<body> 
 <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>
</body>
</html>

Create Controller

Next we need to create application controller.

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.

$ php spark make:controller Member --suffix

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

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

Buy Me a Coffee

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

Learn Web Development Courses @ $4 only.
Web Development Courses @ $4