How to Validate Codeigniter 4 Forms with jQuery Validation

This CodeIgniter 4 jQuery form validation tutorial will show you how to implement client-side validation in Codeigniter 4 application using the jQuery validation library.

Form validation is a significant feature in every web as well as in mobile applications. It helps you receive the correct information that a user sends using the form integrated on your site.

Ideally, the validation is added in two ways client-side validation and server-side validation. The client-side validation is generally implemented for the browsers where users add information on the form input fields, and error messages are displayed when the validation doesn’t meet the appropriate rules.

For the server-side validation, the values submitted by the user are sent to the server and based on the language we use (PHP, Java, ASP). After successful validation, the dynamic response is sent back to the client.

Additionally, we will show you how to add server-side validation in Codeigniter 4 using the built-in Codeigniter services. This simple tutorial will answer the voice reverberating in your head about how to add jQuery validation rules in Codeigniter 4 forms easily.

We will strive hard to provide you with clear, practical guidelines for developing this important feature. You will surely learn how to integrate client-side jQuery validation rules in Codeigniter using the jQuery validation plugin.

There are plenty of plugins, but the unique features of the jQuery validate package makes it the best client-side form validation plugin.

The use of jQuery validate in Codeigniter offers plenty of benefits; it offers a plethora of options; with those options, you can add validation in CodeIgniter within less duration and show validation rules or error messages for specific form field without even reloading or refreshing the whole page.

Codeigniter 4 Form Validation using jQuery Example

  • Step 1: Download Codeigniter Project
  • Step 2: Add Database Credentials
  • Step 3: Insert New Table in Database
  • Step 4: Create Model File
  • Step 5: Register New Routes
  • Step 6: Create Controller File
  • Step 7: Create Form View File
  • Step 8: Run CI App in Browser

Download New Codeigniter Project

Here we are; let’s evoke the first step, so what this section is all about. In this section, you will see how to install the CodeIgniter app using the cli command.

Some of us don’t like the composer way, don’t worry you can download the Codeigniter app manually from their site.

composer create-project codeigniter4/appstarter

Add Database Credentials

To add database credentials for making the connection between app and DB, please open the app/Config/Database.php and update the database details.

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,
    ];

Insert New Table in Database

You see the below SQL command, and this command will create the new table and add columns with form properties in the database.

CREATE TABLE user_form (
    id int(11) NOT NULL AUTO_INCREMENT COMMENT 'Primary Key',
    name varchar(255) NOT NULL COMMENT 'Name',
    email varchar(255) NOT NULL COMMENT 'Email',
    mobile varchar(255) NOT NULL COMMENT 'Mobile',
    message varchar(250) NOT NULL COMMENT 'Message',
    created varchar(20) NOT NULL COMMENT 'Date',
    PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='New table' AUTO_INCREMENT=1;

Create Model File

In the model file, we will define the architecture of the table, so go ahead and create a model file in the app/Models/FormModel.php and make sure to update the provided values.

<?php

namespace App\Models;
use CodeIgniter\Model;

class FormModel extends Model
{

  protected $table = 'user_form';

  protected $allowedFields = [
    'name', 
    'email', 
    'mobile',
    'message'
  ];

}

Register New Routes

The following routes will set the default controller also allow you to execute the controller code.

Go ahead and insert the given code in app/Config/Routes.php file.

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



$routes->setDefaultController('FormController');
$routes->get('/validate-user-form', 'FormController::index');
$routes->match(['get', 'post'], 'FormController/validateForm', 'FormController::validateForm')

Create Controller File

We will create a brand new controller file to handle the server-side validation, storing form values in the DB and loading the view file.

Add code in app/Controllers/FormController.php.

<?php 

namespace App\Controllers;
use CodeIgniter\Controller;
use App\Models\FormModel;


class FormController extends Controller
{

    public function index()
    {    
      return view('index');
    }
 
    public function validateForm()
    {  
        helper(['form', 'url']);
            
        $validate = $this->validate([
            'name' => 'required',
            'email' => 'required',
            'mobile' => 'required',
            'message'  => 'required',
        ]);

        $model = new FormModel();

        if (!$validate)
        {
            echo view('index', [
                'validation' => $this->validator
            ]);
        } else
        {
            $model->save([
                'name' => $this->request->getVar('name'),
                'email'  => $this->request->getVar('email'),
                'mobile'  => $this->request->getVar('email'),
                'message'  => $this->request->getVar('message'),
            ]);

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

Create Form View File

The last segment of this guide will focus on creating the form using Bootstrap, and the jQuery validate plugin.

You will have to add the jQuery validate libraries in the Codeigniter view file, also the Bootstrap library to validate the form.

Add code in app/Views/index.php file.

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

<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>jQuery Form Validation in Codeigniter</title>
	<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
	<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>
</head>

<body>
	<div class="container">
		<form action="<?php echo base_url('FormController/validateForm') ?>"
			name="validateForm" id="validateForm" method="post">
			<div class="mb-2">
				<input type="text" class="form-control" name="name" placeholder="Name">
			</div>
			<div class="mb-2">
				<input type="text" class="form-control" name="email" placeholder="Email">
			</div>
			<div class="mb-2">
				<input type="text" class="form-control" name="mobile" placeholder="Mobile">
				<small class="mt-1"> Use valid us number, like: <strong>+14842989352</strong></small>
			</div>			
			<div class="mb-2">
				<textarea name="message" class="form-control" placeholder="Your message"></textarea>
			</div>
			<div class="d-grid">
				<button type="submit" class="btn btn-dark">Save</button>
			</div>
		</form>
	</div>
	<script>
		if ($("#validateForm").length > 0) {
			$("#validateForm").validate({
				rules: {
					name: {
						required: true,
						minlength: 3,
						maxlength: 50,
					},
					email: {
						required: true,
						email: true,
					},
					mobile: {
						phoneUS: true,
						required: true,
					},
					message: {
						required: true,
						minlength: 10,						
						maxlength: 50,
					},
				},
				messages: {
					name: {
						required: "Please provide name",
						minlength: "Max 3 characters allowed",
						maxlength: "Max 50 characters allowed",
					},
					email: {
						required: "Please provide email",
						email: "Incorrect email format",
					},
					mobile: {
						required: "Please provide email",
					},				
					message: {
						required: "Please enter the message",
						maxlength: "Max 50 characters allowed",
						minlength: "Type min 10 characters",
					},
				},
			})
		}
	</script>
</body>


</html>

Run CI App in Browser

One more time, head over to the console, type the PHP spark command with the serve tab, execute it to start the Codeigniter app.

The provided url start the app on the browser.

php spark serve
http://localhost:8080/validate-user-form

Codeigniter jQuery Forms Validation

Conclusion

We have just finished this Codeigniter 4 Client-Side jQuery Form Validation tutorial; in this guide, we have learned how to integrate jQuery validation rules in Codeigniter 4 form, and we saw the power of jQuery validate plugin, we saw a page that doesn’t have to be reloaded or refreshed while validating the form in Codeigniter.