I'm working on a CodeIgniter 4 project and trying to use a custom validation rule for my form. However, the rule doesn't seem to trigger, and I get no validation errors, even when the input should fail.
Here’s the relevant code:
Custom Rule (App\Validation\CustomRules.php):
namespace App\Validation; class CustomRules { public function noSpecialChars(string $str, string $fields, array $data): bool { return preg_match('/^[a-zA-Z0-9 ]+$/', $str) === 1; } } Validation Configuration (app/Config/Validation.php):
public $ruleSets = [ \CodeIgniter\Validation\Rules::class, \App\Validation\CustomRules::class, ]; Controller Method:
public function submit() { $validation = \Config\Services::validation(); $rules = [ 'username' => 'required|noSpecialChars' ]; if (!$this->validate($rules)) { return redirect()->back()->withInput()->with('errors', $this->validator->getErrors()); } // proceed with saving } Even when I input something like John@Doe, it still passes validation. What am I missing here?
"Argument 2 passed to App\Validation\CustomRules::noSpecialChars() must be of the type string, null given"because you're not passing any parameters to the function in'required|noSpecialChars'. So I'm not sure if this'll solve your problem, but your function signature should look like this:public function noSpecialChars(string $str): bool