Codeigniter 4 Form Validation Tutorial with Example

Last updated on by Digamber
This tutorial explains how to create a form using Bootstrap and form validation in Codeigniter 4 application. There are two types of validation client-side and server-side. We will focus on server-side validation and use Codeigniter’s built-in validation rules to validate a form from scratch.

Codeigniter 4 Form Validation Tutorial

Install / Download Codeigniter 4

There are two ways through which you can make Codeigniter up and running. We are going to look at both the outlooks.

For this step, you must have a composer package installed on your development machine. Execute the below command to install the Codeigniter application with the composer.

composer create-project codeigniter4/appstarter

After installation change the application folder name. I have named it codeigniter-form-validation. Then, get inside the project folder.

cd codeigniter-form-validation

This is the simple and straightforward method. Just click on the following link to easily Download the Codeigniter 4 application.

Show Errors in Codeigniter

To easily debug the application, we will enable the error reporting in our Codeigniter app.

Open app/Config/Boot/development.php file and set the display_errors to 1 instead of 0. Do the same thing in app/Config/Boot/production.php file.

ini_set('display_errors', '1');

Make Database Connection

Add your database name, username and password in application/config/database.php and create the coherence between Database and Codeigniter.

public $default = [
        'DSN'      => '',
        'hostname' => 'localhost',
        'username' => 'test',
        'password' => '4Mu99BhzK8dr4vF1',
        'database' => 'demo',
        '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,
	];

Run the SQL query from PHPMyAdmin to generate users table and along with insert some fake data.

CREATE TABLE `users` (
  `id` int(11) NOT NULL,
  `name` varchar(255) NOT NULL,
  `email` varchar(50) NOT NULL,
  `phone` varchar(20) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CodeIgniter\Database\Exceptions\DatabaseException #8
Unable to connect database : Codeigniter

If anyhow you get the Codeigniter – cannot connect to MySQL database error, then change the hostname value based on your local server e.g MAMPP or XAMPP.

# MAMPP
public $default = [
  ...
     'hostname' => '/Applications/MAMP/tmp/mysql/mysql.sock',
  ...
]

# XAMPP
public $default = [
  ...
     'hostname' => '/Applications/XAMPP/xamppfiles/var/mysql/mysql.sock',
  ...
]

Create New Model

Create app/Models/FormModel.php file in the Models folder, afterwards place the following code.

<?php 
namespace App\Models;
use CodeIgniter\Model;

class FormModel extends Model
{
    protected $table = 'users';
    protected $primaryKey = 'id';
    protected $allowedFields = ['name', 'email', 'phone'];
}

You can play around with various other configuration options to handle Models in Codeigniter.

Create Controller

Now, to handle form validation, we have to create the two essential functions.

The index() function renders the contact form template into the view.

The contactForm() method handles the form of validation and contains various variables. The helper() method manifests autoload helper array.

Create the app/Controllers/FormController.php file and add the given below code in it.

<?php 
namespace App\Controllers;
use App\Models\FormModel;
use CodeIgniter\Controller;

class FormController extends Controller
{

    public function create() {
        return view('contact_form');
    }
 
    public function form() {
        helper(['form', 'url']);
        
        $input = $this->validate([
            'name' => 'required|min_length[3]',
            'email' => 'required|valid_email',
            'phone' => 'required|numeric|max_length[10]'
        ]);

        $formModel = new FormModel();
 
        if (!$input) {
            echo view('contact_form', [
                'validation' => $this->validator
            ]);
        } else {
            $formModel->save([
                'name' => $this->request->getVar('name'),
                'email'  => $this->request->getVar('email'),
                'phone'  => $this->request->getVar('phone'),
            ]);          

            return $this->response->redirect(site_url('/submit-form'));
        }
    }

}

We have added required, min length, max length, valid email, and numeric values validation. However, there are tons of validation options that give impetus to form validation in Codeigniter.

Create Routes

We have to define a route, it will be displaying the contact form and submitting the data in the database on successful form submission. To generate the route insert the following code in the app/Config/Routes.php file.

$routes->get('contact-form', 'FormController::create');
$routes->post('submit-form', 'FormController::formValidation');

Create Form & Show Server Side Errors

Next, let’s create a form with Bootstrap UI framework. We will display server-side errors for every element in the contact form template. Open app/Views/contact_form.php file and place the following code inside of it.

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

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <title>Codeigniter 4 Form Validation Example - positronx.io</title>
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
  <style>
    .container {
      max-width: 550px;
    }
  </style>
</head>

<body>
  <div class="container mt-5">
         
    <?php $validation = \Config\Services::validation(); ?>

    <form method="post" action="<?php echo base_url('/submit-form') ?>">
      <div class="form-group">
        <label>Name</label>
        <input type="text" name="name" class="form-control">

        <!-- Error -->
        <?php if($validation->getError('name')) {?>
            <div class='alert alert-danger mt-2'>
              <?= $error = $validation->getError('name'); ?>
            </div>
        <?php }?>
      </div>
       

      <div class="form-group">
        <label>Email</label>
        <input type="text" name="email" class="form-control">

        <!-- Error -->
        <?php if($validation->getError('email')) {?>
            <div class='alert alert-danger mt-2'>
              <?= $error = $validation->getError('email'); ?>
            </div>
        <?php }?>
      </div>

      <div class="form-group">
        <label>Phone</label>
        <input type="text" name="phone" class="form-control">

        <!-- Error -->
        <?php if($validation->getError('phone')) {?>
            <div class='alert alert-danger mt-2'>
              <?= $error = $validation->getError('phone'); ?>
            </div>
        <?php }?>
      </div>

      <div class="form-group">
        <button type="submit" class="btn btn-primary btn-block">Submit</button>
      </div>
    </form>

  </div>
</body>

</html>

Start the Application

Run the command to start the application:

php spark serve

Enter the following URL in the browser to view the form and form validation:

http://localhost:8080/index.php/contact-form

Summary

Eventually, we have completed the Codeigniter Form Validation tutorial with an example. In this tutorial, we have seen how to implement necessary form validation in the Codeigniter application from scratch. We have gone through every foundational step, and i assume you must have understood every topic gradually.

The entire memoir will surely help us to develop our programming skills in Codeigniter web development. The assortment of every step has been put up in the right place.

I have shared my outlook with you, anyhow you find the lackness of coherence in this tutorial, due to my recklessness, do let me know. I will surely resolve it for you.

You can download the full code of this tutorial from GitHub.