Skip to content

Instantly share code, notes, and snippets.

@lotsofbytes
Last active September 1, 2018 20:21
Show Gist options
  • Save lotsofbytes/3a7ca2dd33e30d2c41b7978123430768 to your computer and use it in GitHub Desktop.
Save lotsofbytes/3a7ca2dd33e30d2c41b7978123430768 to your computer and use it in GitHub Desktop.
[バリデーション:nullable] #laravel #L55 #validation

バリデーション:nullable

指定の項目がなくても、項目の値がなく(空あるいはnull)てもOK。他のルールとともに使用。

laravel 5.5

gistの画面

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

$ git clone git@gist.github.com:3a7ca2dd33e30d2c41b7978123430768.git tests/Unit/Validations/Nullable
<?php
namespace Tests\Unit\Validations\Nullable;
use Tests\TestCase;
use Validator;
class NullableTest extends TestCase
{
/**
* @test
* @dataProvider provider_nullable
*/
public function nullable($input, $expected)
{
$v = Validator::make(
$input,
['field' => 'nullable|string']
);
$this->assertEquals($expected, $v->passes());
}
public function provider_nullable()
{
return [
// 'field'の項目がある
[['field' => null], true],
[['field' => ''], true],
[['field' => ' '], true], // space
[['field' => '値がある'], true],
[['field' => '1234'], true],
[['field' => 1234], false],
// 'field'の項目はない
[['field2' => '値がある'], true],
];
}
/**
* @test
* @dataProvider provider_without_nullable
*/
public function without_nullable($input, $expected)
{
$v = Validator::make(
$input,
['field' => 'string'] // nullableがないとき
);
$this->assertEquals($expected, $v->passes());
}
public function provider_without_nullable()
{
return [
// 'field'の項目がある
[['field' => null], false], // ここが上と違う
[['field' => ''], true],
[['field' => ' '], true], // space
[['field' => '値がある'], true],
[['field' => '1234'], true],
[['field' => 1234], false],
// 'field'の項目はない
[['field2' => '値がある'], true],
];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment