Skip to content

Instantly share code, notes, and snippets.

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

バリデーション:required_unless:anotherfield,value,...

依存する項目(anotherfield)がありその項目に値があり、指定の値(コンマ区切りで複数可:value,...)にマッチしないときに、指定の項目があり値がある(空あるいはnullでない)ならOK。

laravel 5.5

gistの画面

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

$ git clone git@gist.github.com:7d428bd7f174314303a3cb17b99831ca.git tests/Unit/Validations/RequiredUnless
<?php
namespace Tests\Unit\Validations\RequiredUnless;
use Tests\TestCase;
use Validator;
class RequiredUnlessTest extends TestCase
{
/**
* @test
* @dataProvider provider_required_unless
*/
public function required_unless($input, $expected)
{
$v = Validator::make(
$input,
[
'another_field' => 'required',
'field' => 'required_unless:another_field,値1,値2'
]
);
$this->assertEquals($expected, $v->passes());
}
public function provider_required_unless()
{
return [
// 'field'の項目があり、'another_field'の項目があり値もマッチ
[['field' => null, 'another_field' => '値1'], true],
[['field' => '', 'another_field' => '値1'], true],
[['field' => ' ', 'another_field' => '値1'], true], // space
[['field' => '値', 'another_field' => '値1'], true],
[['field' => null, 'another_field' => '値2'], true],
[['field' => '', 'another_field' => '値2'], true],
[['field' => ' ', 'another_field' => '値2'], true], // space
[['field' => '値', 'another_field' => '値2'], true],
// 'field'の項目があり、'another_field'の項目があり値はマッチしない
[['field' => null, 'another_field' => '違う値'], false],
[['field' => '', 'another_field' => '違う値'], false],
[['field' => ' ', 'another_field' => '違う値'], false], // space
[['field' => '値', 'another_field' => '違う値'], true],
];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment