AManInYorkshire's avatar

Error message for custom validator

Hi all.

I have created a form request validator which extends FormRequest. I have several 'standard' rules in use and a custom rule, which I am returning from my rules function as follows:

    public function rules(): array
    {
        return [
            'stake' => 'required|numeric|gt:0',
            'betting_event_ids' => [
                'required',
                'array',
                'min:1',
                'max:14',
                new NoDuplicateFixtures
            ],
...

I am able to set custom messages for the 'standard' rules, but not able to set a message for my custom rule:

    public function messages(): array
    {
        return [
            'betting_event_ids.required' => 'Invalid accumulator - No selections',
            'betting_event_ids.max' => 'Invalid accumulator - Accumulators are restricted to 14 bets',
            'betting_event_ids.NoDuplicateFixtures' => 'a test',
        ];

In the above, 'betting_event_ids.NoDuplicateFixtures' => 'a test',, has no effect. It's clearly not recognising my custom rule class name when setting the errors, which doesn't surprise me, but I can't see how I refer to it otherwise.

I know I can set the message in the custom rule class itself when calling fail(..., but I would like to keep all messages in a single place, and be able to use the same rules in different places with different message.

TIA

:wq

0 likes
3 replies
tykus's avatar
tykus
Best Answer
Level 104

While I don't understand why you would not set the failure message in the Rule class itself, you can override the message by referencing the fully qualified class name for the Rule:

'betting_event_ids.' . NoDuplicateFixtures::class => 'a test',
AManInYorkshire's avatar

@tykus thanks you for that, works perfectly.

FYI the primary reason I want to do this is to be able to use different messages is different situations with the same validator. Being able to override the default from within the validator class like this allows me to do that.

:wq

1 like

Please or to participate in this conversation.