Skip to content
Advertisement

Creating a custom validation error message in CodeIgniter4

How can i create a custom error message for a custom validation. I’m using codeIgniter4

Okay guys so I’m a bit of a newbie with CI4 and I have created a custom validation file using the spark command ./spark make:validation and it works but the problem is I still don’t know how to customize the error message too for instance when I try to validate the date 05-06-2022 the message is Validation.isWeekday, I want to let it say something meaningful like date is not a weekday.

This is how my validation looks like

namespace AppValidation;

class CustomDateValidation
{
    public function isWeekday(string $date): bool
    {
        return date("N", strtotime($date)) < 6;
    }
}

And my controller function looks a bit like this

if($this-validate(['date'=>'required|isWeekday'])){
...
}

Advertisement

Answer

You can pass a options array for each field you want validate instead of just the rules string:

if($this-validate([
  'date'=> [
    'rules' => 'required|isWeekday',
    'errors' => [
       'required' => 'The date field is required',
       'isWeekday' => 'The date must be a weekday'
    ],
  ])){
...
}
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement