blocs/blocs: カスタムバリデーションルールの作成
blocs/blocs: カスタムバリデーションルールの作成
独自のバリデーションルールを作成する方法を説明します。
1. ルールクラスの作成
php artisan make:rule myRule
app/Rules/myRule.php が生成されます。
2. ルールの実装
コンストラクタの定義
BLOCSの data-lang で指定されたメッセージは $message に自動でセットされます。
private $num;
private $message;
public function __construct(string $num, string $message)
{
$this->num = intval($num);
$this->message = $message;
}
バリデーションロジックの定義
public function validate(string $attribute, mixed $value, Closure $fail): void
{
if (intval($value) % $this->num === 0) {
return;
}
$fail($this->message);
}
3. テンプレートでルールを設定
標準ルールと併用可能です。
<!-- !multiples_of_five="bail|required|integer|myRule:5" data-lang="5の倍数を入力してください。" -->
@error("multiples_of_five")
<div class="invalid-feedback">{{ $message }}</div>
@enderror
パラメータを複数渡したい場合
コロン(:)で区切って記述します。
<!-- !range_value="bail|required|integer|myRangeRule:10:100" data-lang="10以上100以下の数値を入力してください。" -->
@error("range_value")
<div class="invalid-feedback">{{ $message }}</div>
@enderror