1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Livewireで動的にバリデーションルールを変更する

Last updated at Posted at 2023-06-20

Livewireでは$rulesプロパティを定義することで、バリデーションルールを設定することができます。

protected $rules = [
    'name' => 'required',
    'email' => 'required|email'
];

public function submit()
{
    // バリデーション実行
    $this->validate();

    // バリデーションで問題なければ続く処理が実行
}

上はあらかじめ決められたルールを適用するケースですが、このルールを動的に変更したい場合(選択肢によって表示される項目が変わるなど)があるかと思います。
その際に思いつくことしては、以下のようにmount時に$rulesを書き換えることかと思いますが、これではバリデーションルールを変更することはできません。

protected $rules = [
    'name' => 'required',
    'email' => 'required|email'
];

public function mount ()
{
    // mount上部で定義したバリデーションルールのままで以下に書き変わらない
    $this->rules = [
        'name' => 'required',
        'email' => 'required|email',
        'postcode' => 'required'
    ];
}

そこで別な方法としては、$rulesプロパティの代わりにメソッドを定義し、mount時に呼び出すことで動的にバリデーションルールを書き換えることができます。

public function mount ()
{
    $this->rules();
}

protected function rules()
{
    //$this->conditionは何かしらのフラグ
    if ($this->condition) {
        return [
            'name' => 'required',
            'email' => 'required|email',
            'postcode' => 'required'
        ];
    } else {
        return [
            'name' => 'required',
            'email' => 'required|email'
        ];
    }
}

[参考]
https://readouble.com/livewire/2.x/ja/input-validation.html

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?