Validation rules help to validate the form. You don’t need to write long if statement conditions for every <form >
element.
CodeIgniter 4 comes equipped with numerous pre-defined validation rules. However, there may be instances where you require custom validation rules designed specifically for your application’s needs.
In this article, we’ll discuss how to create such custom validation rules in CodeIgniter 4. By doing so, you can broaden the framework’s validation capabilities and maintain data accuracy. Follow these steps to seamlessly handle distinct and diverse validation scenarios while extending the validating functionality of your web applications alike.
Table of Content
- Create a Custom Validation Class
- Update Validation.php
- Using Created Custom Validation Class in Controller
- Create Route
- Create a View
- Output
- Conclusion
1. Create a Custom 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 Created Custom Validation Class 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 a View
Create index.php
file in app/Views/
folder.
Create a simple <form >
and set action to <?=site_url('page/submitForm')?>
. Displaying the error message of the custom validation rule is the same as any other built-in validation rule.
<!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
Creating custom validation rules in CodeIgniter 4 is essential to maintain the accuracy and authenticity of user input in web applications. This article outlines steps to help you design rules tailored to your specific requirements, providing flexibility for precise data validation and constraint enforcement. Improved application security and reliability are two benefits of using this approach, ensuring that user input meets essential guidelines.
With CodeIgniter 4’s validation system, users can handle complex validation scenarios with ease. This feature provides an excellent tool that enables the enforcement of business rules and accurate formatting of user inputs. CodeIgniter 4 also allows for custom rule creation, ensuring endless possibilities in data checking. However, it is crucial to adhere to best practices when designing custom rules by ensuring code modularity, reusability and proper documentation.
By mastering custom validation rules in CodeIgniter 4, one takes a major stride towards constructing robust and secure web applications that handle user input validation effectively. Armed with this understanding, individuals can confidently build validation rules that align with their application’s unique requirements and offer users an uninterrupted experience.
If you found this tutorial helpful then don't forget to share.