Home  >  Q&A  >  body text

Create custom validation error messages in CodeIgniter4

<p>How to create a custom error message for custom validation. I'm using codeIgniter4</p> <p>Well I'm new to CI4 and I created a custom validation file using Spark command <code> ./spark make:validation</code> It works but the problem is I still don't know how The error message can also be customized, for example when I try to validate the date 05-06-2022 the message is <strong>Validation.isWeekday</strong> and I want it to say something meaningful like the date is not a weekday . < /p> <p>This is what my verification looks like</p> <pre class="brush:php;toolbar:false;">namespace App\Validation; class CustomDateValidation { public function isWeekday(string $date): bool { return date("N", strtotime($date)) < 6; } } </pre> <p>My controller function looks a bit like this</p> <pre class="brush:php;toolbar:false;">if($this-validate(['date'=>'required|isWeekday'])){ ... } </pre></p>
P粉785957729P粉785957729440 days ago522

reply all(1)I'll reply

  • P粉352408038

    P粉3524080382023-08-29 16:45:45

    You can pass an array of options for each field you want to validate, not just the rule string:

    if($this-validate([
      'date'=> [
        'rules' => 'required|isWeekday',
        'errors' => [
           'required' => 'The date field is required',
           'isWeekday' => 'The date must be a weekday'
        ],
      ])){
    ...
    }

    reply
    0
  • Cancelreply