0
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.

【Laravel】複雑な条件でのバリデーション追加

Posted at

今回は入力値によってバリデーションを分けて表示させたいときの方法について説明します。

一般的なバリデーションの方法についてはこちらの記事を参考にしてください。
https://qiita.com/tomoki1616/items/e344a239ba5e0eac4de3

開発環境
・PHP8.0.8
・Laravel 9.52.8
・MacOS M1チップ

今回やりたいこと

今回やりたいことはユーザーの入力値によってバリデーションを分ける方法です。
例えばAと入力された場合には必須項目とし、Bと入力された場合には任意項目とするみたいな感じです。
複雑なバリデーションに慣れておくことで複雑なシステム開発が可能になります。

withValidatorを使う

複雑な条件下でバリデーションを分けたい場合はwithValidatorを使いましょう。
withValidatorは通常のバリデーション後にバリデーションを追加したいときに便利です。

samleFormRequest.php
namespace App\Http\Requests;

use Illuminate\Validation\Validator;

class samleFormRequest extends FormRequest
{

    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, mixed>
     */
    public function rules():array
    {
        return [
            'name' => 'nullable|max:255',
            'type' => 'nullable|integer'
          ];
    }

    public function withValidator(Validator $validator) {
        $validator->sometimes('name', 'required', function() {
        //typeが1だった場合
        return $this->input('type') == 1;
        });
    }
}

typeが1の場合にnameにバリデーションを追加したい場合は上記の書き方になります。
sometimesの引数として項目、追加したいバリデーション、その条件となります。

参考URL:https://readouble.com/laravel/8.x/ja/validation.html

注意するべきこと(失敗例)

注意するべきことは処理の流れです。
withValidatorは通常のバリデーションの後に処理されるなので、下記のような場合は上手く動作しません。

    public function rules():array
    {
        return [
            'name' => 'required|max:255',
            'type' => 'required|integer'
          ];
    }

    public function withValidator(Validator $validator) {
        $validator->sometimes('name', 'nullable', function() {
        //typeが1だった場合
        return $this->input('type') == 1;
        });
    }

問題はrequirednullableを逆にしていしまっているためです。
先ほども言った通り、withValidatorは通常のバリデーションの後に処理されるので未入力で送信したい場合はrequired でバリデーションにはじかれてしまいます。
こうならないためにも最初をnullablewithValidatorにはrequiredと記載しましょう。

まとめ

バリデーションは運用面で必ず必要になってくる処理の一つです。
複雑な条件下でのバリデーションにも対応できるようにしておくことで、さまざまなシステム開発が可能になります。
僕も勉強した内容を発信していくので、一緒に勉強していきましょう!

0
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
0
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?