Throughout this Codeigniter 4 Form Validation using jQuery tutorial you will learn how to add form validation using jquery in codeigniter application.
Form Validation using jQuery in Codeigniter
Here’s a comprehensive guide to creating a form with jQuery validation in Codeigniter app:
Step 1 – Set Up CodeIgniter 4
Download CodeIgniter 4 from the official site and extract the zip file into the xampp/htdocs
directory. Then, configure the base URL in the app/Config/App.php
file:
public $baseURL = 'http://localhost/your-project/public';
Step 2 – Create the Form
Create a new view file named form_view.php
in the app/Views
directory with the following content:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CodeIgniter 4 Form Validation with jQuery</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
</head>
<body>
<div class="container mt-5">
<h2>Form Validation with jQuery in CodeIgniter 4</h2>
<form id="myForm" method="post" action="<?= base_url('form/submit') ?>">
<div class="form-group">
<label for="name">Name:</label>
<input type="text" class="form-control" id="name" name="name">
<span class="text-danger" id="name-error"></span>
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="text" class="form-control" id="email" name="email">
<span class="text-danger" id="email-error"></span>
</div>
<div class="form-group">
<label for="password">Password:</label>
<input type="password" class="form-control" id="password" name="password">
<span class="text-danger" id="password-error"></span>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</body>
</html>
Step 3 – Add jQuery Validation to the Form
In the form_view.php
file, include jQuery and the jQuery Validation Plugin. Add the following script to handle client-side validation and form submission via AJAX:
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.2/jquery.validate.min.js"></script>
<script>
$(document).ready(function() {
// Initialize jQuery Validation Plugin
$("#myForm").validate({
rules: {
name: {
required: true,
minlength: 3
},
email: {
required: true,
email: true
},
password: {
required: true,
minlength: 6
}
},
messages: {
name: {
required: "Please enter your name",
minlength: "Name must be at least 3 characters long"
},
email: {
required: "Please provide your email address",
email: "Please enter a valid email address"
},
password: {
required: "Please enter your password",
minlength: "Password must be at least 6 characters long"
}
},
errorPlacement: function(error, element) {
var id = element.attr("id") + "-error";
$("#" + id).text(error.text());
},
submitHandler: function(form) {
$.ajax({
url: $(form).attr('action'),
method: 'POST',
data: $(form).serialize(),
dataType: 'json',
success: function(response) {
if (response.status === 'error') {
$('#name-error').text(response.errors.name || '');
$('#email-error').text(response.errors.email || '');
$('#password-error').text(response.errors.password || '');
} else {
alert(response.message);
}
}
});
}
});
});
</script>
Step 4 – Create the Controller
In the app/Controllers
directory, create a controller named FormController.php
:
<?php
namespace App\Controllers;
use CodeIgniter\Controller;
class FormController extends Controller
{
public function index()
{
return view('form_view');
}
public function submit()
{
$validation = \Config\Services::validation();
$validation->setRules([
'name' => 'required|min_length[3]',
'email' => 'required|valid_email',
'password' => 'required|min_length[6]'
]);
if (!$validation->withRequest($this->request)->run()) {
return $this->response->setJSON([
'status' => 'error',
'errors' => $validation->getErrors()
]);
}
return $this->response->setJSON([
'status' => 'success',
'message' => 'Form submitted successfully!'
]);
}
}
Step 5 – Define Routes
Edit the app/Config/Routes.php
file to set up the necessary routes:
$routes->get('/', 'FormController::index');
$routes->post('form/submit', 'FormController::submit');
Step 6 – Test the Application
Start the application server with the following command:
cd /your-project
php spark serve
Visit http://localhost:8080
in your browser to test the form and its validation functionality.