📡 You're offline — showing cached content
New version available!
Quick Access
Tutorials CodeIgniter 4 Validation CI4

Validation CI4

5 min read Quiz at the end
Validate input with rules like required, valid_email, is_unique, and uploaded for file uploads.

Validation in CI4

// In controller
$rules = [
    "name"     => "required|min_length[2]|max_length[100]",
    "email"    => "required|valid_email|is_unique[users.email]",
    "password" => "required|min_length[8]",
    "age"      => "required|is_natural|greater_than[17]",
    "avatar"   => "permit_empty|uploaded[avatar]|is_image[avatar]|max_size[avatar,2048]",
];

if (!$this->validate($rules)) {
    return redirect()->back()->withInput()
                     ->with("errors", $this->validator->getErrors());
}

// Separate validation class
// app/Validation/UserRules.php
class UserRules {
    public function uniquePhone(string $str, string $fields, array $data, ?string &$error): bool {
        $exists = db()->table("users")->where("phone", $str)->countAllResults();
        if ($exists > 0) { $error = "Phone already registered"; return false; }
        return true;
    }
}

// Custom error messages
$messages = ["email.valid_email" => "Please enter a real email address."];
Topic Quiz · 2 questions

Test your understanding before moving on

1. Which rule validates a unique database value?
💡 is_unique[users.email] checks the value does not exist in users.email.
2. What method returns validation error messages?
💡 $this->validator->getErrors() returns an array of field => message pairs.