0

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?

1
  • 1
    If I set up a CI4 project with the code from your post, it gives me a TypeError for the validation rule "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 Commented Jun 26 at 8:09

1 Answer 1

2

@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].

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.