🛡️ Advanced Validation Techniques
Mastering Input Validation in CodeIgniter 4
Input validation is a crucial part of building secure and reliable applications. In CodeIgniter 4, the validation library provides advanced tools to validate form inputs efficiently and prevent malicious data from entering your system.
✅ Built-in Validation Rules
- required – Ensures a field is not empty
- valid_email – Validates proper email format
- min_length[n] – Enforces minimum character count
- matches[field] – Confirms two fields match
🧪 Example Validation in Controller
if (! $this->validate([
'username' => 'required|min_length[5]',
'email' => 'required|valid_email',
'password' => 'required|min_length[8]'
])) {
return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
}
🛠️ Creating Custom Validation Rules
Sometimes built-in rules aren’t enough. CodeIgniter 4 lets you define custom rules easily.
🔧 Step 1: Create Rule Class
// app/Validation/MyRules.php
namespace App\Validation;
class MyRules
{
public function alpha_dash_space(string $str, string $fields, array $data): bool
{
return (bool) preg_match('/^[a-zA-Z0-9 _-]+$/', $str);
}
}
🔧 Step 2: Register in Config
// app/Config/Validation.php
public $ruleSets = [
\CodeIgniter\Validation\Rules::class,
\App\Validation\MyRules::class,
];
🔧 Step 3: Use the Rule
'fullname' => 'required|alpha_dash_space'
📦 Handling Validation Errors
You can use the validator error bag in views to display specific errors.
<?php if (session()->has('errors')) : ?>
<div class="alert alert-danger">
<ul>
<?php foreach (session('errors') as $error) : ?>
<li><?= $error ?></li>
<?php endforeach; ?>
</ul>
</div>
<?php endif; ?>
🧠 Pro Tip: Unique Field Validation
'email' => 'required|valid_email|is_unique[users.email]'
Make sure your database table and field names are correct when using is_unique
.
🧩 Conclusion
CodeIgniter 4 provides robust, scalable validation options for both beginners and advanced developers. With the ability to create custom rules, handle error messages, and validate directly in models or controllers — you’re equipped to build secure and user-friendly forms with confidence.
🚀 Want More CodeIgniter 4 Tricks?
Subscribe or follow to stay ahead in modern web development.
Visit BlogHappy Validating! 🛠️
0 Comments