Skip to content

Instantly share code, notes, and snippets.

@lotsofbytes
Last active October 6, 2018 20:08
Show Gist options
  • Save lotsofbytes/6a409d6165a125b7af51cd87360a8c34 to your computer and use it in GitHub Desktop.
Save lotsofbytes/6a409d6165a125b7af51cd87360a8c34 to your computer and use it in GitHub Desktop.
[バリデーション:max] #laravel #L55 #validation

バリデーション:max

入力値が、指定の最大値以下の値であることを判定。入力値が、文字列なら文字数、配列ならその個数がサイズとなる。 文字列を数値としての扱いたいなら、numericあるいはintegerが前ルールとして必要(例:integer|size:4)。

laravel 5.5

gistの画面

以下の実行で、ダウンロードできます

$ git clone git@gist.github.com:6a409d6165a125b7af51cd87360a8c34.git tests/Unit/Validations/Max
<?php
namespace Tests\Unit\Validations\Max;
use Tests\TestCase;
use Validator;
class MaxTest extends TestCase
{
/**
* @test
* @dataProvider provider_max
*/
public function max($input, $expected)
{
$v = Validator::make(
$input,
['field' => 'required|max:4']
);
$this->assertEquals($expected, $v->passes());
}
public function provider_max()
{
return [
// 文字列なら長さ
[['field' => '000'], true],
[['field' => '0000'], true],
[['field' => 'abcd'], true],
[['field' => '00000'], false],
// 配列なら個数
[['field' => ['a', 'b', 'c']], true],
[['field' => ['a', 'b', 'c', 'd']], true],
[['field' => ['a', 'b', 'c', 'd', 'e']], false],
];
}
/**
* @test
* @dataProvider provider_max_numeric
*/
public function max_numeric($input, $expected)
{
$v = Validator::make(
$input,
['field' => 'required|numeric|max:4'] // numericが必要
);
$this->assertEquals($expected, $v->passes());
}
public function provider_max_numeric()
{
return [
// 数字なら整数
[['field' => '3'], true],
[['field' => '4'], true],
[['field' => '0004'], true],
[['field' => '3.9'], true],
[['field' => '4.9'], false]
];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment