LaravelのFormRequestで上書きできるカスタムRuleを作成する方法について記載。
以下のような独自に作成したRuleクラスをvalidateに使用する場合、
ContactFormRequestクラスに記載しているようなmessagesの上書きは反映されずに、
AlphaNumCheckクラスに記載の元のmessageが表示されてしまう。
・ContactFormRequestクラス
use Illuminate\Foundation\Http\FormRequest;
class ContactFormRequest extends FormRequest
{
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'number' => ['required', new AlphaNumCheck()],
];
}
public function attributes()
{
return [
'number' => '数値',
];
}
public function messages()
{
return [
'number.*' => ':attribute 上書きしたメッセージ',
];
}
}
・Ruleクラス
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
class AlphaNumCheck implements Rule
{
/**
* 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('/^[a-zA-Z0-9]+$/', $value);
}
/**
* Get the validation error message.
*
* @return string
*/
public function message()
{
return '元のメッセージ';
}
}
これだと、Ruleを使用するFormRequestによってメッセージを変えられないので、
作成した独自Ruleでかつ、上書き可能な方法を記載。
(上記のAlphaNumCheckクラスを流用する)
・ App\Providers\AppServiceProviderのboot()にバリデーションの処理と登録名称を記載
public function boot()
{
Validator::extend('alpha_num_check','App\Rules\AlphaNumCheck@passes');
}
・ContactFormRequestクラスのrules()で登録したrule名を指定
use Illuminate\Foundation\Http\FormRequest;
class ContactFormRequest extends FormRequest
{
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'number' => ['required','alpha_num_check'],
];
}
public function attributes()
{
return [
'number' => '数値',
];
}
public function messages()
{
return [
'number.*' => ':attribute 上書きしたメッセージ',
];
}
}
これで、バリデーションに引っかかった場合にContactFormRequestに記載のmessagesで上書きされます。
以上