Codeigniter provides the form helper to validate the form. You can easily validate the inputs like name, email, password, and many more fields. In the entire form validation process, the form will submit to the specified action. While submitting the form to the action, it will check the form inputs as per the specified rules. Here, we will see the step-by-step process of the form validation in Codeigniter 4. Before submitting the form, we have to create a form first. If you are a complete beginner in Codeigniter 4 then you must start with my previous post. In this series, I already started from very scratch from the CRUD Application in CodeIgniter 4. So, without taking more time, let’s dive into the example by creating a new project in Codeigniter 4.
Prerequisites
If you want to create a new project in Codeigniter 4 then you must have the following requirements-
- PHP >= 7.3
- MySQL (version > 5)
- Apache/Nginx Server
- VS Code Editor
- Composer
Create a New Project For Form Validation in Codeigniter 4
For creating the new project, I will be using composer. You can create the Codeigniter 4 project using the composer too. I already shown you in my last tutorial of Codeigniter 4. Hence, open the terminal and hit the below command.
composer create-project codeigniter4/appstarter form-validation
The above command will create a new folder as I specified the project name. Then inside the folder, it will install the Codeigniter 4 setup and necessary files.
After creating the project, let’s create a database in MySQL.
How to Install CodeIgniter 4 in Windows and Linux
Create and Configure Database in Codeigniter 4
I am going to create a new database in MySQL. Hence, you can create a database by hitting the below command.
CREATE DATABASE ci4_form;
After creating the database, just open the Codeigniter project into the editor. Then follow the below steps-
- Rename the env file to .env.
- Change the environment to development from production.
- Now, under the database section, you will find the default database configuration.
#--------------------------------------------------------------------
# DATABASE
#--------------------------------------------------------------------
database.default.hostname = localhost
database.default.database = ci4_form
database.default.username = root
database.default.password = root
database.default.DBDriver = MySQLi
In the next step, we will create a migration for the users table. Actually, I will be creating a basic user registration form. Then, I will implement the form validation on it.
Create Migration For Form Validation in Codeigniter 4
You can create a migration for the table schema in Codeigniter 4. I have already shown you in my last Codeigniter 4 tutorial. So, inside the project, open the terminal and hit the below command.
php spark make:migration users --table
The above command will create a migration file for the users inside the app/Database/Migrations folder.
Here, I have added the necessary fields for the form validation. You can take a look, if required then you may add more fields. I am just going to show you the basic concept for the form validation.
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
class Users extends Migration
{
public function up()
{
$this->forge->addField([
'id' => [
'type' => 'INT',
'auto_increment' => true
],
'name' => [
'type' => 'VARCHAR',
'constraint' => '30'
],
'email' => [
'type' => 'VARCHAR',
'constraint' => '50'
],
'password' => [
'type' => 'VARCHAR',
'constraint' => '20'
],
'phone' => [
'type' => 'VARCHAR',
'constraint' => '15'
],
'address' => [
'type' => 'TEXT'
],
'created_at datetime default current_timestamp',
'updated_at datetime default current_timestamp on update current_timestamp'
]);
$this->forge->addKey('id', true);
$this->forge->createTable('users');
}
public function down()
{
$this->forge->dropTable('users');
}
}
After putting the schema of the users migration, let’s migrate it using below command.
php spark migrate
On the migration, the specified tables will be created into the database.
How to Create Github Login in Laravel 8 Using Socialite
Create Model in Codeigniter 4
In Codeigniter 4, you can create a model using spark. So, according to our project, we will create one model for the user. Actually, we already created the migration for the users table. Hence, open the terminal and create a new model file.
php spark make:model User
The above command will create a model for the user.
Once you created the model, make it look like this.
<?php
namespace App\Models;
use CodeIgniter\Model;
class User extends Model
{
protected $DBGroup = 'default';
protected $table = 'users';
protected $primaryKey = 'id';
protected $useAutoIncrement = true;
protected $protectFields = true;
protected $allowedFields = ['name', 'email', 'password', 'phone', 'address'];
// Dates
protected $useTimestamps = false;
protected $dateFormat = 'datetime';
protected $createdField = 'created_at';
protected $updatedField = 'updated_at';
}
After filling up the allowed fields in the User model, we will move to the next step.
How to Create Login with Twitter in Laravel 8 Using Socialite
Create a Controller For Form Validation in Codeigniter 4
For getting the inputs from the form, we required a controller. After reading the form data, we will set the validation rules on those inputs. In Codeigniter 4, you can create a controller using the spark command.
php spark make:controller UserController
Here, the UserController has been created. Now, let’s put the functionality on it.
<?php
namespace App\Controllers;
use App\Controllers\BaseController;
class UserController extends BaseController
{
/**
* constructor
*/
public function __construct()
{
helper(['form', 'url']);
}
/**
* User Registration form
*
* @return void
*/
public function index()
{
return view('registration');
}
/**
* Register User
*
* @return void
*/
public function create() {
$inputs = $this->validate([
'name' => 'required|min_length[5]',
'email' => 'required|valid_email',
'password' => 'required|min_length[5]|alpha_numeric',
'confirm_password' => 'required|matches[password]',
'phone' => 'required|numeric|regex_match[/^[0-9]{10}$/]',
'address' => 'required|min_length[10]'
]);
if (!$inputs) {
return view('registration', [
'validation' => $this->validator
]);
}
}
}
The above functions will require the routes. So, in the next step, we will be creating the routes.
Create LinkedIn Login in Laravel 8 Using Socialite
Create Routes For Form Validation in Codeigniter 4
For creating the routes, just open the app/Config/Routes.php file. Now, put the below routes there.
$routes->get('user', 'UserController::index');
$routes->post('user', 'UserController::create');
After adding the routes, we will create a view for the User Registration.
Create Socialite Login with Google Account in Laravel 8
Create a View For Form Handling
You have to create a form for the validation of inputs. Hence, for creating a form, you need a view that will contain the form. Hence, create a view inside the app/Views folder. I am going to create a view with the name registration.php.
<!doctype html>
<html lang="en">
<head>
<title>Codeigniter 4 Form Validation Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- bootstrap 5 CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.4.1/font/bootstrap-icons.css">
</head>
<body>
<div class="container py-4">
<?php $validation = \Config\Services::validation(); ?>
<div class="row">
<div class="col-xl-6 col-lg-6 col-md-6 col-sm-12 col-12 m-auto">
<form method="POST" action="<?= base_url('user') ?>">
<?= csrf_field() ?>
<div class="card shadow">
<div class="card-header">
<h5 class="card-title">Register User</h5>
</div>
<div class="card-body p-4">
<div class="form-group mb-3 has-validation">
<label class="form-label">Name</label>
<input type="text" class="form-control <?php if($validation->getError('name')): ?>is-invalid<?php endif ?>" name="name" placeholder="Name" value="<?php echo set_value('name'); ?>"/>
<?php if ($validation->getError('name')): ?>
<div class="invalid-feedback">
<?= $validation->getError('name') ?>
</div>
<?php endif; ?>
</div>
<div class="form-group mb-3">
<label class="form-label">Email</label>
<input type="text" class="form-control <?php if($validation->getError('email')): ?>is-invalid<?php endif ?>" name="email" placeholder="Email" value="<?php echo set_value('email'); ?>"/>
<?php if ($validation->getError('email')): ?>
<div class="invalid-feedback">
<?= $validation->getError('email') ?>
</div>
<?php endif; ?>
</div>
<div class="form-group mb-3">
<label class="form-label">Password</label>
<input type="password" class="form-control <?php if($validation->getError('password')): ?>is-invalid<?php endif ?>" name="password" placeholder="Password" value="<?php echo set_value('password'); ?>"/>
<?php if ($validation->getError('password')): ?>
<div class="invalid-feedback">
<?= $validation->getError('password') ?>
</div>
<?php endif; ?>
</div>
<div class="form-group mb-3">
<label class="form-label">Confirm Password</label>
<input type="password" class="form-control <?php if($validation->getError('confirm_password')): ?>is-invalid<?php endif ?>" name="confirm_password" placeholder="Confirm Password" value="<?php echo set_value('confirm_password'); ?>"/>
<?php if ($validation->getError('confirm_password')): ?>
<div class="invalid-feedback">
<?= $validation->getError('confirm_password') ?>
</div>
<?php endif; ?>
</div>
<div class="form-group mb-3">
<label class="form-label">Phone</label>
<input type="text" class="form-control <?php if($validation->getError('phone')): ?>is-invalid<?php endif ?>" name="phone" placeholder="Phone" value="<?php echo set_value('phone'); ?>"/>
<?php if ($validation->getError('phone')): ?>
<div class="invalid-feedback">
<?= $validation->getError('phone') ?>
</div>
<?php endif; ?>
</div>
<div class="form-group">
<label class="form-label">Address</label>
<textarea class="form-control <?php if($validation->getError('address')): ?>is-invalid<?php endif ?>" name="address" placeholder="Address"><?php echo set_value('address'); ?></textarea>
<?php if ($validation->getError('address')): ?>
<div class="invalid-feedback">
<?= $validation->getError('address') ?>
</div>
<?php endif; ?>
</div>
</div>
<div class="card-footer">
<button type="submit" class="btn btn-success">Save</button>
</div>
</div>
</form>
</div>
</div>
</div>
</body>
</html>
Save and run the application to see the result.
How to Create Facebook Login in Laravel 8 Using Socialite
Check the Validation Result
Open the favorite browser and run the Codeigniter project. Go to the http://localhost:8080/user
. You will see a registration form as showing below.
We have already set the validation rules for this form. Now, let’s try submitting the form. As per the validation rules, you will be getting the error message in the form.
In the above validation error message, you can notice one thing. The validation error message is throwing on the basis of the input name. Suppose, for the Password Confirmation, the input name is confirm_password. Hence, the validation error message for this has thrown on the basis of the same name. So, what if we want to change this label of validation error message.
How to Schedule Tasks with Cron Job in Laravel 8
Change Label For Validation Error Message in Codeigniter 4
We can change the label of every inputs for displaying the error message. It will make more meaningful to our form validation. So, you have to add the attribute in the form of array as showing below.
$inputs = $this->validate([
'name' => ['label' => 'Name', 'rules' => 'required|min_length[5]'],
'email' => ['label' => 'Email', 'rules' => 'required|valid_email'],
'password' => ['label' => 'Password', 'rules' => 'required|min_length[5]|alpha_numeric'],
'confirm_password' => ['label' => 'Confirm Password', 'rules' => 'required|matches[password]'],
'phone' => ['label' => 'Mobile number', 'rules' => 'required|numeric|regex_match[/^[0-9]{10}$/]'],
'address' => ['label' => 'Address', 'rules' => 'required|min_length[10]']
]);
Import and Export CSV and Excel File in Laravel 8
Set Custom Validation Error Message
In the Codeigniter form validation, you can set the custom validation error message. It is really very simple to has a custom message for every rule. For creating the custom validation error message, you can put the errors attribute ins the form of an array.
So, let’s see how you can achieve this.
$inputs = $this->validate([
'name' => [
'label' => 'Name',
'rules' => 'required|min_length[5]',
'errors' => [
'required' => 'Please enter your name.',
'min_length' => 'Name must be atleast 5 characters long.'
]
],
'email' => [
'label' => 'Email',
'rules' => 'required|valid_email',
'errors' => [
'required' => 'Enter your email.',
'valid_email' => 'Please enter a valid email address.'
]
],
'password' => [
'label' => 'Password',
'rules' => 'required|min_length[5]|alpha_numeric',
'errors' => [
'required' => 'Enter your password.',
'min_length' => 'Password must be atleast 5 digits.',
'alpha_numeric' => 'Password must contain alpha numeric'
]
],
'confirm_password' => [
'label' => 'Confirm Password',
'rules' => 'required|matches[password]',
'errors' => [
'required' => 'Re-enter your password.',
'matches' => 'Confirm password and password must be same.'
],
],
'phone' => [
'label' => 'Mobile number',
'rules' => 'required|numeric|regex_match[/^[0-9]{10}$/]',
'errors' => [
'required' => 'Enter your mobile number.',
'numeric' => 'Mobile number must be a number.',
'regex_match' => 'Mobile number must be a valid mobile number.'
]
],
'address' => [
'label' => 'Address',
'rules' => 'required|min_length[10]',
'errors' => [
'required' => 'Enter your address.',
'min_length' => 'Address must be atleast 10 characters long.'
]
]
]);
Save and run the application. Now, re-check the validation errors by submitting the form.
Also, you can see the custom validation error message for every specific rule.
After the validation, you can insert the data through the model. So, let’s add few lines of code after the validation rules.
$user = new User;
$user->save([
'name' => $this->request->getVar('name'),
'email' => $this->request->getVar('email'),
'password' => $this->request->getVar('email'),
'phone' => $this->request->getVar('phone'),
'address' => $this->request->getVar('address')
]);
session()->setFlashdata('success', 'Success! registration completed.');
return redirect()->to(site_url('/user'));
In the above snippet, I have created an object of the User model class. Then using the save() method, I have inserted the data in the form of array.
We have to display the flash data message to the view. So, just add few lines in the Views/registration.php.
<!-- display flash data message -->
<?php
if(session()->getFlashdata('success')):?>
<div class="alert alert-success alert-dismissible">
<button type="button" class="btn-close" data-bs-dismiss="alert">×</button>
<?php echo session()->getFlashdata('success') ?>
</div>
<?php elseif(session()->getFlashdata('failed')):?>
<div class="alert alert-danger alert-dismissible">
<button type="button" class="btn-close" data-bs-dismiss="alert">×</button>
<?php echo session()->getFlashdata('failed') ?>
</div>
<?php endif; ?>
Now, you will have the result of success after inserting the data.
So, the final snippet of the UserController.php will be as showing below.
<?php
namespace App\Controllers;
use App\Controllers\BaseController;
use App\Models\User;
class UserController extends BaseController
{
/**
* constructor
*/
public function __construct()
{
helper(['form', 'url']);
}
/**
* User Registration form
*
* @return void
*/
public function index()
{
return view('registration');
}
/**
* Register User
*
* @return void
*/
public function create() {
// validate inputs
$inputs = $this->validate([
'name' => [
'label' => 'Name',
'rules' => 'required|min_length[5]',
'errors' => [
'required' => 'Please enter your name.',
'min_length' => 'Name must be atleast 5 characters long.'
]
],
'email' => [
'label' => 'Email',
'rules' => 'required|valid_email',
'errors' => [
'required' => 'Enter your email.',
'valid_email' => 'Please enter a valid email address.'
]
],
'password' => [
'label' => 'Password',
'rules' => 'required|min_length[5]|alpha_numeric',
'errors' => [
'required' => 'Enter your password.',
'min_length' => 'Password must be atleast 5 digits.',
'alpha_numeric' => 'Password must contain alpha numeric'
]
],
'confirm_password' => [
'label' => 'Confirm Password',
'rules' => 'required|matches[password]',
'errors' => [
'required' => 'Re-enter your password.',
'matches' => 'Confirm password and password must be same.'
],
],
'phone' => [
'label' => 'Mobile number',
'rules' => 'required|numeric|regex_match[/^[0-9]{10}$/]',
'errors' => [
'required' => 'Enter your mobile number.',
'numeric' => 'Mobile number must be a number.',
'regex_match' => 'Mobile number must be a valid mobile number.'
]
],
'address' => [
'label' => 'Address',
'rules' => 'required|min_length[10]',
'errors' => [
'required' => 'Enter your address.',
'min_length' => 'Address must be atleast 10 characters long.'
]
]
]);
if (!$inputs) {
return view('registration', [
'validation' => $this->validator
]);
}
// insert data
$user = new User;
$user->save([
'name' => $this->request->getVar('name'),
'email' => $this->request->getVar('email'),
'password' => password_hash($this->request->getVar('password'), PASSWORD_DEFAULT),
'phone' => $this->request->getVar('phone'),
'address' => $this->request->getVar('address')
]);
session()->setFlashdata('success', 'Success! registration completed.');
return redirect()->to(site_url('/user'));
}
}
Now, after adding the flash data message in the registration.php (view), it will look like this.
<!doctype html>
<html lang="en">
<head>
<title>Codeigniter 4 Form Validation Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- bootstrap 5 CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.4.1/font/bootstrap-icons.css">
</head>
<body>
<div class="container py-4">
<?php $validation = \Config\Services::validation(); ?>
<div class="row">
<div class="col-xl-6 col-lg-6 col-md-6 col-sm-12 col-12 m-auto">
<form method="POST" action="<?= base_url('user') ?>">
<?= csrf_field() ?>
<!-- display flash data message -->
<?php
if(session()->getFlashdata('success')):?>
<div class="alert alert-success alert-dismissible">
<button type="button" class="btn-close" data-bs-dismiss="alert">×</button>
<?php echo session()->getFlashdata('success') ?>
</div>
<?php elseif(session()->getFlashdata('failed')):?>
<div class="alert alert-danger alert-dismissible">
<button type="button" class="btn-close" data-bs-dismiss="alert">×</button>
<?php echo session()->getFlashdata('failed') ?>
</div>
<?php endif; ?>
<div class="card shadow">
<div class="card-header">
<h5 class="card-title">Register User</h5>
</div>
<div class="card-body p-4">
<div class="form-group mb-3 has-validation">
<label class="form-label">Name</label>
<input type="text" class="form-control <?php if($validation->getError('name')): ?>is-invalid<?php endif ?>" name="name" placeholder="Name" value="<?php echo set_value('name'); ?>"/>
<?php if ($validation->getError('name')): ?>
<div class="invalid-feedback">
<?= $validation->getError('name') ?>
</div>
<?php endif; ?>
</div>
<div class="form-group mb-3">
<label class="form-label">Email</label>
<input type="text" class="form-control <?php if($validation->getError('email')): ?>is-invalid<?php endif ?>" name="email" placeholder="Email" value="<?php echo set_value('email'); ?>"/>
<?php if ($validation->getError('email')): ?>
<div class="invalid-feedback">
<?= $validation->getError('email') ?>
</div>
<?php endif; ?>
</div>
<div class="form-group mb-3">
<label class="form-label">Password</label>
<input type="password" class="form-control <?php if($validation->getError('password')): ?>is-invalid<?php endif ?>" name="password" placeholder="Password" value="<?php echo set_value('password'); ?>"/>
<?php if ($validation->getError('password')): ?>
<div class="invalid-feedback">
<?= $validation->getError('password') ?>
</div>
<?php endif; ?>
</div>
<div class="form-group mb-3">
<label class="form-label">Confirm Password</label>
<input type="password" class="form-control <?php if($validation->getError('confirm_password')): ?>is-invalid<?php endif ?>" name="confirm_password" placeholder="Confirm Password" value="<?php echo set_value('confirm_password'); ?>"/>
<?php if ($validation->getError('confirm_password')): ?>
<div class="invalid-feedback">
<?= $validation->getError('confirm_password') ?>
</div>
<?php endif; ?>
</div>
<div class="form-group mb-3">
<label class="form-label">Phone</label>
<input type="text" class="form-control <?php if($validation->getError('phone')): ?>is-invalid<?php endif ?>" name="phone" placeholder="Phone" value="<?php echo set_value('phone'); ?>"/>
<?php if ($validation->getError('phone')): ?>
<div class="invalid-feedback">
<?= $validation->getError('phone') ?>
</div>
<?php endif; ?>
</div>
<div class="form-group">
<label class="form-label">Address</label>
<textarea class="form-control <?php if($validation->getError('address')): ?>is-invalid<?php endif ?>" name="address" placeholder="Address"><?php echo set_value('address'); ?></textarea>
<?php if ($validation->getError('address')): ?>
<div class="invalid-feedback">
<?= $validation->getError('address') ?>
</div>
<?php endif; ?>
</div>
</div>
<div class="card-footer">
<button type="submit" class="btn btn-success">Save</button>
</div>
</div>
</form>
</div>
</div>
</div>
</body>
</html>
That’s it for the form validation in Codeigniter 4.
Conclusion
In this Codeigniter 4 tutorial, I have shown you the basic idea of validating the form. You can create a large number of inputs in any form and set the validation rules on it. I also, shown you to set the custom error message for every specific validation rule. You can use regular expression to validation on any specific patter. As, we did for the mobile number validation. Therefore, I hope, you can take a quick guide for Codeigniter 4 form validation.
Joshua Otwell says
Great blog post. Very informative and well written.
Umesh Rana says
Hi Joshua, Thank you for your compliment. Keep visiting for the updated content.
Acak Kadut says
Very good information, thank you for your article Umesh! it really helpfull to us