What is CI4 custom validation rules?
Why Interviewers Ask This
This is a differentiating question used for senior and lead roles. Interviewers want to see if you can explain not just what happens, but why — and what the trade-offs are in different approaches.
Answer
CodeIgniter 4 allows creating custom validation rules for business-specific checks. Method 1 — Ruleset class: create a class with rule methods and register in app/Config/Validation.php under $ruleSets: protected $ruleSets = ["App\Validation\CustomRules"]. The rule method signature: public function validPhoneNumber(string $value, string $params, array $data, string &$error): bool — return false and set $error to show a message. Use: "phone" => "required|valid_phone_number". Method 2 — Closure rules (CI4.3+): $validation->setRule("code", "Code", [function($value, $data, &$error) { if (!preg_match("/^[A-Z]{3}-[0-9]{4}$/", $value)) { $error = "Invalid code format"; return false; } return true; }]). Rule parameters: "min_value[10]" — in the method, $params receives "10". Custom rules integrate seamlessly with CI4's validation pipeline.
Common Mistake
Rushing to answer is a common mistake. Take two seconds to structure your response: definition → example → trade-off. This structure makes complex CodeIgniter answers easy to follow.