Validation rules help to validate the form. You don’t need to write long if statement conditions for every <form >
element.
While validating your form elements if your requirement is not fulfilled with the inbuilt validation rules provided then you can create your own validation rules.
In this tutorial, I show how you can create a custom validation rule and use it in the controller in the CodeIgniter 4 project.
Contents
- Create Validation Class
- Update Validation.php
- Using Custom validation in Controller
- Create Route
- Create View
- Output
- Conclusion
1. Create Validation Class
I am creating a custom class for defining validations. I will create 2 methods to explain rule creation with and without parameter.
- Create
CustomValidation.php
file inapp/Config/
folder. - Create
CustomValidation
class. - In the class, every created method is a rule. So, name your method related to your validation.
- Create 2 methods –
- validusername() – This method is without a parameter type of rule. While using you do not need to pass extra parameter.
This method has 2 parameters –
-
-
- $str – It has an element value.
- $error – Using this you can return an error message.
-
Check if username has a valid value using preg_match()
. If it has then return true
otherwise return false
and assign an error message to $error
variable.
-
- checkmax() – This method is a parameter type of rule. While using you need to pass an extra parameter.
This method has 3 parameters –
-
-
- $str – It has element value.
- $field – It has passed parameter value.
- $data – Using this you can access other element values e.g.
$data['minvalue']
.
-
You cannot define $error
as 4 parameter similar to the 1st method.
If $str
value is less than $data[$field]
then return false
otherwise, return true
.
Completed Code
<?php namespace Config; class CustomValidation{ public function validusername(string $str, ?string &$error = null): bool { $usernamePreg = "/^[a-zA-Z0-9]+$/"; if( (preg_match($usernamePreg,$str))) { return true; } $error = "Please enter valid username"; return false; } public function checkmax($str, string $field, array $data): bool { if($str < $data[$field]){ return false; } return true; } }
2. Update Validation.php
Need to mention created custom validation class in Validation.php
for using it.
- Open
app/Config/Validation.php
file. - Include
Config\CustomValidation;
. - Specify
CustomValidation::class,
in$ruleSets
Array.
Completed Code
<?php namespace Config; use CodeIgniter\Config\BaseConfig; use CodeIgniter\Validation\CreditCardRules; use CodeIgniter\Validation\FileRules; use CodeIgniter\Validation\FormatRules; use CodeIgniter\Validation\Rules; use Config\CustomValidation; // Custom validation class Validation extends BaseConfig { // -------------------------------------------------------------------- // Setup // -------------------------------------------------------------------- /** * Stores the classes that contain the * rules that are available. * * @var string[] */ public $ruleSets = [ Rules::class, FormatRules::class, FileRules::class, CreditCardRules::class, CustomValidation::class, // Custom Validation ]; /** * Specifies the views that are used to display the * errors. * * @var array<string, string> */ public $templates = [ 'list' => 'CodeIgniter\Validation\Views\list', 'single' => 'CodeIgniter\Validation\Views\single', ]; // -------------------------------------------------------------------- // Rules // -------------------------------------------------------------------- }
3. Using Custom validation in Controller
- Create
PagesController
Controller.
php spark make:controller PagesController
- Create 2 methods –
- index() – Load
index
view. - submitForm() – This method calls on form submit.
- index() – Load
Define validation on submitted values –
-
-
- name – Set
required
rule. - username – Set
required
rule and also set created custom validation rule –validusername
. - minvalue – Set
required
andnumeric
rule. - maxvalue – Set
required
andnumeric
rule. Also, set custom validation rule with parameter –checkmax[minvalue]
. Here,minvalue
is<form >
element name. You can also pass value instead of element name –checkmax[300]
.
- name – Set
-
If <form >
is not validated then return to the page with validation messages otherwise, set SESSION
flash and redirect to route('/')
.
Completed Code
<?php namespace App\Controllers; use App\Controllers\BaseController; class PagesController extends BaseController { public function index(){ return view('index'); } public function submitForm(){ // Validation $input = $this->validate([ 'name' => 'required', 'username' => 'required|validusername', 'minvalue' => 'required|numeric', 'maxvalue' => 'required|numeric|checkmax[minvalue]', ],[ 'maxvalue' => [ 'checkmax' => 'Max value must be greater than min value', ] ]); if (!$input) { // Not valid $data['validation'] = $this->validator; return redirect()->back()->withInput()->with('validation', $this->validator); }else{ // Set Session session()->setFlashdata('message', 'Submitted Successfully!'); session()->setFlashdata('alert-class', 'alert-success'); } return redirect()->route('/'); } }
4. Create Route
- Open
app/Config/Routes.php
file. - Here, create 2 routes –
- /
- page/submitForm – Handle form submit.
$routes->get('/', 'PagesController::index'); $routes->post('page/submitForm', 'PagesController::submitForm');
5. Create View
Create index.php
file in app/Views/
folder.
Create a simple <form >
and set action to <?=site_url('page/submitForm')?>
.
Completed Code
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>How to create custom validation Rule in CodeIgniter 4</title> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" > </head> <body> <div class="container"> <div class="row"> <div class="col-md-6 mt-5" style="margin: 0 auto;"> <?php // Display Response if(session()->has('message')){ ?> <div class="alert <?= session()->getFlashdata('alert-class') ?>"> <?= session()->getFlashdata('message') ?> </div> <?php } ?> <?php $validation = \Config\Services::validation(); ?> <form method="post" action="<?=site_url('page/submitForm')?>"> <?= csrf_field(); ?> <div class="form-group mb-4"> <label class="control-label col-sm-2" for="name">Name:</label> <div class="col-sm-10"> <input type="text" class="form-control" id="name" placeholder="Enter Name" name="name" value="<?= old('name') ?>"> </div> <!-- Error --> <?php if( $validation->getError('name') ) {?> <div class='text-danger mt-2'> * <?= $validation->getError('name'); ?> </div> <?php }?> </div> <div class="form-group mb-4"> <label class="control-label col-sm-2" for="username">Username:</label> <div class="col-sm-10"> <input type="text" class="form-control" id="username" placeholder="Enter Username" name="username" value="<?= old('username') ?>"> </div> <!-- Error --> <?php if( $validation->getError('username') ) {?> <div class='text-danger mt-2'> * <?= $validation->getError('username'); ?> </div> <?php }?> </div> <div class="form-group mb-4"> <label class="control-label col-sm-2" for="minvalue">Min value:</label> <div class="col-sm-10"> <input type="text" class="form-control" id="minvalue" placeholder="Enter Min value" name="minvalue" value="<?= old('minvalue') ?>"> </div> <!-- Error --> <?php if( $validation->getError('minvalue') ) {?> <div class='text-danger mt-2'> * <?= $validation->getError('minvalue'); ?> </div> <?php }?> </div> <div class="form-group mb-4"> <label class="control-label col-sm-2" for="maxvalue">Max value:</label> <div class="col-sm-10"> <input type="text" class="form-control" id="maxvalue" placeholder="Enter Max value" name="maxvalue" value="<?= old('maxvalue') ?>" > </div> <!-- Error --> <?php if( $validation->getError('maxvalue') ) {?> <div class='text-danger mt-2'> * <?= $validation->getError('maxvalue'); ?> </div> <?php }?> </div> <div class="form-group "> <div class="col-sm-offset-2 col-sm-10"> <button type="submit" class="btn btn-info">Submit</button> </div> </div> </form> </div> </div> </div> </body> </html>
6. Output
7. Conclusion
Using this you can write your own validation rules that you are not able to perform with inbuilt validation rules.
In the example, I have created a single Class file for creating validation rules but you can also do this with multiple class files.
Make sure to update Validation.php
after the custom validation file creation otherwise, you cannot use it.