CodeIgniter 4 jQuery Client Side Form Validation Tutorial

Last Updated on by in CodeIgniter

In this Codeigniter 4 Bootstrap 5 contact form validation tutorial, we will teach you how to add client-side validation in simple contact form within the Codeigniter application with the help of the jQuery validate js and Bootstrap CSS plugins.

We will not just show you how to implement jQuery client-side validation in contact form.

But also explain to you how to create thank you page or form submission page and redirect to thank you page after the form is successfully submitted using the good old simple techniques.

The validate js is a very powerful and easy to use client-side form validation plugin; it offers tons of customization options.

It makes your validation work facile due to the wide array of validation options, and yes, it supports more than 35 languages.

How to Validate Form in Codeigniter 4 using jQuery

  • Step 1: Create Codeigniter App
  • Step 2: Enable Error Handling
  • Step 3: Create Contact Form Table
  • Step 4: Connect to Database
  • Step 5: Set Up New Model
  • Step 6: Create Contact Form Controller
  • Step 7: Add Route
  • Step 8: Create Form View
  • Step 9: Run Codeigniter Project

Create Codeigniter App

Composer plays crucial role in codeigniter web application development, its a go-to tool that install and download various types of packages and Codeigniter fresh or new applications.

Don’t bother to run the suggested command to install a new app.

composer create-project codeigniter4/appstarter

After the installation is done, don’t forget to change the name of the codeigniter app.

Likewise, you may easily download the Codeigniter app straight from their official website.

Enable Error Handling

To quickly and easily debug the unwonted errors requires you to update the display_errors property, head over to app/Config/Boot/development.php and app/Config/Boot/production.php files and change the display_errors to 1 from 0.

ini_set('display_errors', '1');

Create Contact Form Table

A new table requires to be added to the database; this table will contain the contact form information. Make sure to use the SQL query to formulate the new table with id, name, email, message, and created_date properties.

CREATE TABLE contact_form (
    id int(11) NOT NULL AUTO_INCREMENT COMMENT 'Primary Key',
    name varchar(150) NOT NULL COMMENT 'Name',
    email varchar(255) NOT NULL COMMENT 'Email',
    message varchar(250) NOT NULL COMMENT 'Message',
    created_at varchar(20) NOT NULL COMMENT 'Date Created',
    PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='contact form table' AUTO_INCREMENT=1;

Connect to Database

This step will establish the consent between Codeigniter and the database; this is an easy process and requires you to include the database name, username, and password in the app/Config/Database.php file.

public $default = [
        'DSN'      => '',
        'hostname' => 'localhost',
        'username' => 'root',
        'password' => '',
        'database' => 'codeigniter_db',
        '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,
    ];

CodeIgniter\Database\Exceptions\DatabaseException

Seldom, you might get Unable to connect database: Code-igniter error. If you are one of the user of either MAMP or XAMP, you can add the respective local server value as the hostname.

# ====== MAMP
public $default = [
  ...

  'hostname' => '/Applications/MAMP/tmp/mysql/mysql.sock',
]

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

Set Up New Model

In this segment, you have to create a model file that will hold the logical structure of the contact form table.

Head over to the app/Models/ folder within the path, create the new model file and name it ContactFormModel.php file.

Update the app/Models/ContactFormModel.php file.

<?php 

namespace App\Models;
use CodeIgniter\Database\ConnectionInterface;
use CodeIgniter\Model;
 
class ContactFormModel extends Model
{
    protected $table = 'contact_form';
    protected $allowedFields = [
        'name', 
        'email', 
        'message'
    ];
}

Create Contact Form Controller

Next, get ready and create a new controller file, primarily head over to the app/Controllers directory, construct a new file, name it ContactFormController.php.

Then add the following code inside the app/Controllers/ContactFormController.php file.

<?php 

namespace App\Controllers;

use CodeIgniter\Controller;
use App\Models\ContactFormModel;
 
class ContactFormController extends Controller
{
    public function index()
    {    
      return view('contact_form');
    }
 
    public function form()
    {  
        helper(['form', 'url']);
            
        $isValid = $this->validate([
            'name' => 'required',
            'email' => 'required',
            'message'  => 'required',
        ]);

        $contactFormModel = new ContactFormModel();

        if (!$isValid)
        {
            echo view('contact_form', [
                'validation' => $this->validator
            ]);
        } else
        {
            $contactFormModel->save([
                'name' => $this->request->getVar('name'),
                'email'  => $this->request->getVar('email'),
                'message'  => $this->request->getVar('message'),
            ]);

            echo view('thank_you');
        }
    }
}

Let me break down how we set up the logical structure in the controller file; the index() method loads the contact form template into the view. Whereas, the form() function is handling the validation and submitting the contact form values to the server.

Add Route

In this section, we will add the routes to invoke the form template in the view, consequently, open the app/Config/Routes.php, even more, define the following code within the file.

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



$routes->setDefaultController('ContactFormController');
$routes->get('/', 'ContactFormController::index');
$routes->match(['get', 'post'], 'ContactFormController/form', 'ContactFormController::form')

Create Form View

In this step, you will create the form structure using Bootstrap 5, integrate the form with the database and validate every field of the contact form using the validate js.

Now, get into the app/Views directory, there you need to create a new view file, name it contact_form.php add the following code inside the app/Views/contact_form.php file.

<!DOCTYPE html>
<html>

<head>
    <title>Codeigniter 4 jQuery Form Validation Demo</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0/dist/css/bootstrap.min.css">
    <style>
        .error {
            width: 100%;
            margin-top: .25rem;
            font-size: .875em;
            color: #dc3545;
        }
    </style>
</head>

<body>
    <div class="container mt-5" style="max-width: 500px">
        <form id="contact_form" method="post" action="<?php echo base_url('ContactFormController/form') ?>"
            name="contact_form">
            <div class="form-group mb-3">
                <label class="fw-bold mb-2">Name</label>
                <input type="text" name="name" class="form-control">
            </div>
            <div class="form-group mb-3">
                <label class="fw-bold mb-2">Email</label>
                <input type="text" name="email" class="form-control">
            </div>
            <div class="form-group mb-3">
                <label class="fw-bold mb-2">Message</label>
                <textarea name="message" class="form-control"></textarea>
            </div>
            <div class="d-grid">
                <button type="submit" class="btn btn-primary">Submit</button>
            </div>
        </form>
    </div>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/jquery-validation@1.19.3/dist/jquery.validate.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/jquery-validation@1.19.3/dist/additional-methods.min.js"></script>
    <script>
        if ($("#contact_form").length > 0) {
            $("#contact_form").validate({
                rules: {
                    name: {
                        required: true
                    },
                    email: {
                        required: true,
                        email: true,
                        maxlength: 60
                    },
                    message: {
                        required: true,
                    },
                },
                messages: {
                    name: {
                        required: "Name is required",
                    },
                    email: {
                        email: "It doe not seem valid email",
                        required: "Email is required",
                        maxlength: "Upto 50 characters are allowed",
                    },
                    message: {
                        required: "Please, enter the query",
                    },
                },
            })
        }
    </script>
</body>

</html>

Further, move to the app/Views directory again, create a new file, give it name such as thank_you.php. After that, add the given below code in app/Views/thank_you.php file.

This template is being used for showing the thank you message to the user on successful form submission, its a kind of authentication that reveals that the form has been successfully submitted.

<!DOCTYPE html>
<html>

<head>
    <title> Codeigniter 4 Form Submitted - Thank You Page </title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0/dist/css/bootstrap.min.css">
</head>

<body>
    <div class="container mt-5" style="max-width: 500px">
        <div class="alert alert-success text-center" role="alert">
            <h2>Your message has been received!</h2>
        </div>
    </div>
</body>

</html>

Run Codeigniter Project

Running a Codeigniter app is exorbitantly easy; similarly, the codeigniter development server can be started using a single command.

php spark serve

To test the app use the following url.

http://localhost:8080

jQuery form validation in codeigniter

Conclusion

Forms are used more than often in web and mobile applications, forms are the best tool to get user’s information.

However, adding client-side validation is as much required as the server-side; in this Codeigniter jQuery form validation example.

We have comprehended how to throughly yet profoundly add client-side validation to the contact form or simple form using the jQuery validation plugin. So, this is it, we have finished Codeigniter 4 jQuery form validation example, have a good day.