I am using Laravel 8.75 and I want to validate fields. I have created a custom rule to validate money.
The rule looks like this:
<?php
namespace AppRules;
use IlluminateContractsValidationRule;
class FlexibalCurrencyRule implements Rule
{
private $regex = '/^([0-9]{1,10})([.,][0-9]{1,2})?$/';
/**
* Create a new rule instance.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Determine if the validation rule passes.
*
* @param string $attribute
* @param mixed $value
* @return bool
*/
public function passes($attribute, $value)
{
return preg_match($this->regex, $value);
}
/**
* Get the validation error message.
*
* @return string | array
*/
public function message()
{
return "currency";
}
}
It is very plain and simple. Then in my controllers I do the following:
$requestDto = json_decode($request->getContent(), true);
$validator = Validator::make($requestDto, [
'name' => 'required|max:100',
'price' => ['required', new FlexibalCurrencyRule],
]);
if ($validator->fails()) {
// Send response to browser
}
When I call the endpoint my validation messages contain the following:
"price": {
"App\Rules\FlexibalCurrencyRule": []
}
As you can see Laravel doesn’t call the message() function. It just prints the class name. From what I understand it should call the message() function and return ‘currency’ as the validation rule. How can I convert a custom rule into a string message instead of the class name being returned?