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 バリデーション integerは数値の1でも文字列の1でも通過する

Posted at

概要

  • integerバリデーションは指定されたキーの値が「整数なのか否か」をチェックしている。なので数値の1でも文字列の1でもintegerバリデーションは通過する。
  • どうして整数なら何でも通すのかを確認してみる。

内容

  • そもそもintegerバリデーションルールのチェックは下記で判定されている。

    • vendor/laravel/framework/src/Illuminate/Validation/Concerns/ValidatesAttributes.phpvalidateInteger()メソッド
  • 当該メソッドの内容を下記に抜粋する。

    ValidatesAttributes.php
    /**
     * Validate that an attribute is an integer.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function validateInteger($attribute, $value)
    {
        return filter_var($value, FILTER_VALIDATE_INT) !== false;
    }
    
  • どうやらPHPの組み込み関数であるfilter_var関数で値のチェックしているっぽい。

  • filter_var関数の第2引数に渡しているフィルターの型で「FILTER_VALIDATE_INT」を指定している。当該フィルターの型は引数が整数の場合その値を、それ以外はfalseを返すらしい。

  • なので、そもそもチェックするメソッドそのものが数値の1でも、文字列の1でも通過するようにチェックしてるっぽい。

  • 実際にfilter_var関数を使って遊んで見る。

    <?php
    // Your code here!
    
    $int = 2;
    $str = '2';
    $strFoo = 'aa';
    
    var_dump(filter_var($int, FILTER_VALIDATE_INT)); // int(2)
    var_dump(filter_var($str, FILTER_VALIDATE_INT)); // int(2)
    var_dump(filter_var($strFoo, FILTER_VALIDATE_INT)); // bool(false)
    
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?