验证两种结果的所有可能性

时间:2018-08-21 22:26:58

标签: laravel laravel-validation

所以我得到了两个结果的回调:

positive: url.com?scope=read_write&code={AUTHORIZATION_CODE}&state={csrf}

negative: url.com?error=access_denied&error_description=The%20user%20denied%20your%20request

我想验证所有可能性。我目前的方法是:

$data = request()->validate([
  'scope' => 'required_without:error, error_description',
  'code' => 'required_without:error, error_description',
  'state' => 'required_without:error, error_description',

  'error' => 'required_without:scope,code,state',
  'error_description' => 'required_without:scope,code,state'
]);

实际上,它对每种可能性都非常有效,但对于某种可能性却不可行:

$this->get(route('connect.index', [
    'error' => $this->error,
    'error_description' => $this->error_description,
]));

dd(session('errors'));

奇怪的部分是我得到了错误:

  #messages: array:3 [
        "scope" => array:1 [
          0 => "The scope field is required when error / error description is not present."
        ]
        "code" => array:1 [
          0 => "The code field is required when error / error description is not present."
        ]
        "state" => array:1 [
          0 => "The state field is required when error / error description is not present."
        ]
      ]

但这是不正确的,因为我看到存在错误值error_description!

array(2) {
  ["error"]=>
  string(2) "ok"
  ["error_description"]=>
  string(5) "state"
}

更新

@DigitalDrifter帮助了我,但是现在,我有两个失败的新测试用例!

$this->get(route('connect.index', [
    'scope' => $this->scope,
    'code' => $this->code,
    'error' => $this->error,
    'error_description' => $this->error_description,
]))
    ->assertStatus(302);

$this->get(route('connect.index', [
    'scope' => $this->scope,
    'code' => $this->code,
    'state' => $this->error,
    'error_description' => $this->error_description,
]))
    ->assertStatus(302);

您可能会看到我期望得到302的响应,但我得到200。情况并非如此。我正在使用@DigitalDrifter答案:

$data = request()->validate([
        'scope' => 'bail|sometimes|required_without:error,error_description',
        'code' => 'bail|sometimes|required_without:error,error_description',
        'state' => 'bail|sometimes|required_without:error,error_description',

        'error' => 'bail|required_without:scope,code,state',
        'error_description' => 'bail|required_without:scope,code,state',
    ]);

1 个答案:

答案 0 :(得分:1)

可能{@ {3}}有好运:

  

存在时进行验证
  在某些情况下,仅当输入数组中存在该字段时,您才可能希望对该字段运行验证检查。要快速完成此操作,请将有时会使用的规则添加到规则列表中:

$data = request()->validate([
  'scope'             => 'bail|sometimes|required_without:error,error_description',
  'code'              => 'bail|sometimes|required_without:error,error_description',
  'state'             => 'bail|sometimes|required_without:error,error_description',
  'error'             => 'bail|required_without:scope,code,state',
  'error_description' => 'bail|required_without:scope,code,state'
]);