Codeigniter 4 Server Side Form Validation Tutorial Example

In this Codeigniter 4 form validation example, we will assist you how to implement server-side form validation in Codeigniter 4 app from scratch.

Codeigniter form validation tutorial; Codeigniter comes loaded with Form Helper; ideally, the primary role of Form Helper is to solve validation related problems.

Form validation deals with a technical process and checks the form values, and makes sure whether the information provided by the user is authentic or not.

Form helper helps you validate the form input values like name, email, phone number, password etc. On clicking on the submit button, forma validation does its job and display the error message to the user and let them know what they did wrong and fix it ASAP to proceed further.

You will be given bit by bit information on using form validation in Codeigniterthe 4 app, not just that we will also cover form validation with error alert messages.

Codeigniter 4 Form Validation with Display Error Message Example

  • Step 1: Create Codeigniter App
  • Step 2: Establish Database Connection in Codeigniter
  • Step 3: Create Table in DB
  • Step 4: Setting Up Model File
  • Step 5: Setting Up Form Controller
  • Step 6: Register New Routes
  • Step 7: Create Form View File
  • Step 8: Run App in Browser

Create Codeigniter App

The initial step is about downloading a brand new Codeigniter app; you can do it with the given command.

Furthermore, you can install Codeigniter app manually from the website.

composer create-project codeigniter4/appstarter

Establish Database Connection

A further task is to establish Codeigniter and database connection; make sure to update the DB credentials in app/Config/Database.php.

public $default = [
        'DSN'      => '',
        'hostname' => 'localhost',
        'username' => 'db_username',
        'password' => 'db_password',
        'database' => 'db_name',
        'DBDriver' => 'MySQLi',
        'DBPrefix' => '',
        'pConnect' => false,
        'DBDebug'  => (ENVIRONMENT !== 'development'),
        'cacheOn'  => false,
        'cacheDir' => '',
        'charset'  => 'utf8',
        'DBCollat' => 'utf8_general_ci',
        'swapPre'  => '',
        'encrypt'  => false,
        'compress' => false,
        'strictOn' => false,
        'failover' => [],
        'port'     => 3306,

Create Table in DB

After validating the form, we have to store the user-provided values into the database. For that, you must have a table created in the DB for storing the values.

Ensure you run the given command from the PHPMyAdmin’s SQL console.

CREATE TABLE `contacts` (
  `id` int(11) NOT NULL,
  `name` varchar(255) NOT NULL,
  `email` varchar(100) NOT NULL,
  `mobile` varchar(15) NOT NULL

Setting Up Model File

Once the database and table have been created, next move on to the Models folder, create a modal file.

Define table name and the values into the app/Models/Contact.php file.


namespace App\Models;

use CodeIgniter\Model;

class Contact extends Model

  protected $table = 'contacts';

    protected $allowedFields = [


Controller Formation

The crucial role of the controller is to lay the foundation of business logic; for instance you have to define the index() and store methods in the app/Controllers/ContactController.php.

namespace App\Controllers;

use CodeIgniter\Controller;
use App\Models\Contact;

class ContactController extends Controller

    public function index() {
        return view('index');
    public function store() {
        helper(['form', 'url']);
        $isValidated = $this->validate([
            'name' => 'required|min_length[2]',
            'email' => 'required|valid_email',
            'mobile' => 'required|max_length[12]|numeric'

        $contact = new Contact();
        if (!$isValidated) {
            echo view('index', [
                'validation' => $this->validator
        } else {
                'name' => $this->request->getVar('name'),
                'email'  => $this->request->getVar('email'),
                'mobile'  => $this->request->getVar('mobile'),

            return $this->response->redirect(site_url('/contact'));


Register New Routes

Formation of new routes is essential; they process the controller logic and retrieve the response in the browser.

Go ahead define the routes simultaneously with GET and POST methods in the app/Config/Routes.php.

 * --------------------------------------------------------------------
 * Route Definitions
 * --------------------------------------------------------------------

$routes->get('/contact', 'ContactController::index');
$routes->post('/validate-form', 'ContactController::store');

Create Form View File

We will create the list of the users and fetch the data dynamically from the database and represent the data on the frontend using the datatable widget.

Thus, create view file and update code in app/Views/index.php file.

<!DOCTYPE html>
<html lang="en">

	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>Codeigniter 4 Form Validation Integration Example</title>
	<link href="" rel="stylesheet">
		.container {
			max-width: 500px

	<div class="container">
		<?php $validation = \Config\Services::validation(); ?>
		<form method="post" action="<?php echo base_url('/validate-form') ?>">
			<div class="mb-3">
				<input type="text" name="name" class="form-control" placeholder="Name">

				<?php if($validation->getError('name')) {?>
				<div class='text-danger mt-1'>
					<?= $error = $validation->getError('name'); ?>
				<?php }?>

			<div class="mb-3">
				<input type="text" name="email" class="form-control" placeholder="Email">

				<?php if($validation->getError('email')) {?>
				<div class='text-danger mt-1'>
					<?= $error = $validation->getError('email'); ?>
				<?php }?>

			<div class="mb-3">
				<input type="text" name="mobile" class="form-control" placeholder="Mobile">

				<?php if($validation->getError('mobile')) {?>
				<div class='text-danger mt-1'>
					<?= $error = $validation->getError('mobile'); ?>
				<?php }?>

			<div class="d-grid">
				<button type="submit" class="btn btn-dark">Send</button>


Run App in Browser

The view has been properly created and set up; now, you have to put less effort into the next task and run the command to view the app in the browser.

php spark serve

Codeigniter 4 Form Validation


If you are a novice developer and strived hard to understand how to get started with form validation in Codeigniter.

We can guarantee you this example of form validation in CodeIgniter will enlighten you towards the righteous path with the formal process of dealing with server-side form validation in Codeigniter.