Working on an existing project, so keeping the code structure the same as other developers is critical.
I've created a new Rule
and added my Validator::extend
to the boot()
. However I can't get the validation error to display my custom message. Instead is just displays a default "validation.ruleName"
I'm writing a Validation rule that uses ImLiam's NHS Number validation package. The validate()
and passes()
work successfully. But the error message never changes.
How can I get the messages()
method to display the custom output of the exception? (Instead of "validation.nhsnumber" in screenshot below?
App\Forms\MyForm: (using Kris Forms)
public function buildForm()
{
$this->add('nhs_number', 'number', [
'label' => 'NHS Number',
'rules' => 'nullable|nhsnumber',
]);
...
}
App\Providers\AppServiceProvider:
public function boot()
{
Validator::extend('nhsnumber', \App\Rules\ValidNhsNumber::class);
}
App\Rules\ValidNhsNumber:
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
use ImLiam\NhsNumber\InvalidNhsNumberException;
use ImLiam\NhsNumber\NhsNumber;
class ValidNhsNumber implements Rule
{
private $message;
/**
* 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): bool
{
try {
$nhsNumber = new NhsNumber($value);
$nhsNumber->validate(); // Will throw exception here if false
return true;
} catch (InvalidNhsNumberException $e) {
$this->message = $e->getMessage();
}
}
public function validate($attribute, $value, $params): bool
{
return $this->passes($attribute, $value);
}
/**
* Get the validation error message.
*
* @return string
*/
public function message()
{
return $this->message;
}
}