laravel-enum icon indicating copy to clipboard operation
laravel-enum copied to clipboard

Custom validation message for EnumValue

Open alexandruu opened this issue 3 years ago • 4 comments

Hy,

I have a Form Request with a custom validation rule:

$rules = [ 'input.value' => ['required', new EnumValue(ValueEnum::class, false)], ];

Validation works fine but the message received is ambiguous:

The value you have entered is invalid.

Is there a way to change this message to include at least the attribute in it?

alexandruu avatar Dec 07 '21 10:12 alexandruu

Hi @alexandruu, you can set a specific message using the messages method on your form request as per the Laravel docs: https://laravel.com/docs/8.x/validation#customizing-the-error-messages

e.g.

public function messages()
{
    return [
        'input.value.enum_value' => 'Your custom validation message',
    ];
}

Or you can change it for your whole project by following the localization instructions: https://github.com/BenSampo/laravel-enum#localization

BenSampo avatar Dec 07 '21 11:12 BenSampo

Thanks for the reply, @BenSampo !

I've tried with method messages() and first I didn't know how to target the class EnumValue() from the conditions. After your reply I've tested with input.value.enum_value but the received message hasn't changed:

The value you have entered is invalid.

Is there another way to target the class EnumValue() from the conditions?

alexandruu avatar Dec 07 '21 11:12 alexandruu

It works if you use the pipe syntax: https://github.com/BenSampo/laravel-enum#pipe-validation

But not if you use the class syntax - I'll have to look into that.

BenSampo avatar Dec 07 '21 12:12 BenSampo

With pipe syntax it's working! Thank you very much, @BenSampo !

$rules = [ 'input.value' => 'required|enum_value:' . ValueEnum::class];

and method

public function messages()
{
    return [
        'input.value.enum_value' => 'Your custom validation message',
    ];
}

it's producing:

Your custom validation message

alexandruu avatar Dec 07 '21 12:12 alexandruu

When used as an object, EnumValue falls back to the same translation key as the pipe syntax based rule. It just requires that the language files were published.

spawnia avatar Dec 07 '22 09:12 spawnia