LoginSignup
1
1

laravel バリデーション in

Last updated at Posted at 2022-06-18

概要

  • POSTされた値が指定した値のいずれかであることをバリデートするバリデーションルールinをまとめる。

記載方法

  • 下記のように記載することでinバリデーションルールを設定できる。

  • 配列で指定する方法(POSTされた値が0 or 1であることをバリデートするルール)

    formRequest.php
    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'content' => ['in:0,1'],
        ];
    }
    
  • 配列で指定する方法(POSTされた値がint型の0 or int型の1であることをバリデートするルール)

    formRequest.php
    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'content' => ['integer', 'in:0,1'],
        ];
    }
    
  • Ruleバリデーションルールクラスを用いる方法 (POSTされた値が0 or 1であることをバリデートするルール)

    formRequest.php
    use Illuminate\Validation\Rule;
    
    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'content' => Rule::in([0, 1]),
        ];
    }
    
  • もちろん文字列も指定可能

    formRequest.php
    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'content' => ['in:foo,var'],
        ];
    }
    
  • 文字列でinバリデーションを用いるならstringバリデーションも併用したほうがよいかもしれない

    formRequest.php
    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'content' => ['string', 'in:foo,var'],
        ];
    }
    

応用

  • 本バリデーションルールを用いれば、受け取る値を限定する事ができる。「指定した単独の値しか通過させたくない」場合に使える。

  • 例えばcontentの値を1のみ通したい場合、下記のようにinの引数で配列で1だけを指定すれば「1は通す、1以外は通さない」ことが可能

    formRequest.php
    use Illuminate\Validation\Rule;
    
    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'content' => Rule::in([1]),
        ];
    }
    
  • 配列で指定すると下記のようになる。多分こちらのほうが一般的

    formRequest.php
    use Illuminate\Validation\Rule;
    
    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'content' => [in:1],
        ];
    }
    

参考文献

1
1
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
1