29
13

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 3 years have passed since last update.

Laravelバリデーション integerとnumericの動作の違い

Last updated at Posted at 2020-11-27
  • Laravel6.x
  • PHP7.4

紛らわしいので調べました。

integer の挙動

入力値が整数で構成された文字列か数値であることをバリデートします。

※実際の判定文はこちら

// vendor\laravel\framework\src\Illuminate\Validation\Concerns\ValidatesAttributes.php
public function validateInteger($attribute, $value)
{
    return filter_var($value, FILTER_VALIDATE_INT) !== false;
}

numericの挙動

入力値が数字または数値形式の文字列であることをバリデートします。

※実際の判定文はこちら

// vendor\laravel\framework\src\Illuminate\Validation\Concerns\ValidatesAttributes.php
public function validateNumeric($attribute, $value)
{
    return is_numeric($value);
}

比較

  • ○:バリデーションチェックを通過する
  • ×:バリデーションチェックに引っかかりエラーになる
検証値 integer numeric regex:/^[0-9]+$/i
'0'
'123'
'0123' × 注意!
'+1' ○ 注意! ×
'-1' ○ 注意! ×
'0.1' × ×
'1.1' × ×
'113-0012' × × ×
'090-111-222' × × ×
'123' × × ×

おまけ 動作確認用

<?php
$list = ['0', '123', '0123', '+1', '-1', '0.1', '1.1', '114-0012', '090-2222-3333', '123'];
foreach ($list as $value) {
    echo "$value ";
    if (filter_var($value, FILTER_VALIDATE_INT) !== false) {
        echo " |integer: ○";
    } else {
        echo " |integer: ×";
    }    
    
    if (is_numeric($value)) {
        echo " |numeric: ○";
    } else {
        echo " |numeric: ×";
    }
    
    if (preg_match("/^[0-9]+$/i", $value)) {
        echo " |regex: ○";
    } else {
        echo " |regex: ×";
    }

    echo "\n";
}
?>
29
13
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
29
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?