phpcodeignitervalidationcodeigniter-4

Why is my CodeIgniter 4 custom validation rule not working in form validation?


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?


Solution

  • @Marleen is correct. You have too many parameters in your noSpecialChars function. I have a similar function in my CI4 app that looks like this:

    public function alpha_numeric_punct_german(string $str, ?string &$error = null)
    {
        // M = Math_Symbol, P = Punctuation, L = Latin
        if ((bool) preg_match('/^[^\p{M}\p{P}\p{L}\p{N} €]+$/u', $str)) {
            $error = 'Contains illegal characters';
    
            return false;
        }
    
        return true;
    }
    

    The $errorargument is optional. You only have to pass string $fields and array $data if you want to pass additional data to your validation rule like for example in in_list[2,5] or valid_date[d.m.Y].