LoginSignup
2
0

More than 1 year has passed since last update.

laravel バリデーション sometimes

Last updated at Posted at 2022-06-18

概要

  • キーが送信された場合のみ設定されているバリデーションチェックを行うsometimesについてまとめる。

記載方法

  • このバリデーションは若干filledと似ている。

  • しかしfilledは「キーが送られた場合、空ではないこと」をバリデートしている。

  • 今回のsomeimesは「キーが送られた場合、その他の設定されているバリデーションチェックを行う」というルールである。

  • キーが有るときだけ 「filledは空でないことだけのチェックを実施」「sometimesは空でないことを含むその他のチェックを実施する事ができる(その他のバリデーション設定次第)」という違いのようだ。

  • 下記のように記載する。(content_1のキーが送られた場合「'required', 'integer'」のチェックが行われる。)

    formRequest.php
    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'content_1' => ['sometimes', 'required', 'integer'],
        ];
    }
    
  • ちなみにバリデーションsometimesを一番最初に指定しないと行けないわけでない。下記でも上記と同じ動作をする。

    formRequest.php
    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'content_1' => ['required', 'integer', 'sometimes'],
        ];
    }
    
  • さらに、sometimesを用いてfilledと同じチェックをする事ができる。(多分同じチェックになっているはず。動作的には変わらなかった。)

  • sometimesを使用

    formRequest.php
    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'content_1' => ['sometimes', 'required'],
        ];
    }
    
  • filledを使用

    formRequest.php
    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'content_1' => ['filled'],
        ];
    }
    
2
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
2
0