LoginSignup
2
2

More than 5 years have passed since last update.

【バリデーション】2つのカラムのどちらか一方は必須としたい。

Last updated at Posted at 2017-10-30

2つカラムがあって、どちらか片方は必須としたい。
ここでしか使わないんだからValidatorの拡張はめんどくさい。あぁ、めんどうだ。

下のソースの場合、telかemailのどちらか片方は入力して欲しい。ちなみに、timeはtelが入力されたら必須です。

Controllerに書く。

InquiryController.php

                 // ベースとなるルール
        $rules = [
            'name' => 'required|max:255',
            'tel' => 'sometimes|numeric|max:14',
            'time' => 'required_with:tel',
            'email' => 'sometimes|max:255|email',
            'text' => 'max:1024',
        ];
        // 電話番号かメアドかのどちらかは必須
        if (is_null($request['tel']) || is_null($request['email'])) {
            // 電話番号が空の場合、電話番号のバリデーションをクリアし、メアドのバリデーションを追加する。
            if (is_null($request['tel'])) {
                $rules['email'] = 'required_without:tel|sometimes|max:255|email';
                $rules['tel'] = '';
            }
            // メアドが空の場合、メアドのバリデーションをクリアし、電話番号のバリデーションを追加する。
            if (is_null($request['email'])) {
                $rules['tel'] = 'required_without:email|sometimes|numeric|max:14';
                $rules['email'] = '';
            }

        }
        $validator = Validator::make($request->all(), $rules);

telもemailも入力されていないと「emailが指定されていない場合、telを指定してください。」と表示されます。
telは入力ありで、timeが未選択だと「telが指定されている場合、timeも指定してください。」と出ます。
ここはもう少し考えよう……。

と、自分メモでした。

[追記]
おまけです。
エラーメッセージのtelとかtimeとか、日本語にしました。
これの下の方に「attributes」ってあるので、その配列のところに定義します。

resources/lang/ja/validation.php
    'attributes' => [
        'email' => 'メールアドレス',
        'name' => '名前',
        'tel' => '電話番号',
        'time' => '連絡可能時間帯',
        'text' => 'その他ご要望等',
    ],
2
2
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
2
2