laravel-enum
laravel-enum copied to clipboard
Custom validation message for EnumValue
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?
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
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?
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.
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
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.