【发布时间】:2019-10-29 20:50:32
【问题描述】:
我有一个想要验证的数组。 post json 有效负载如下所示
{
"guid" : "d19b122dc48a4663e33eaa7c83993f7a40ae9329",
"organization" : {
"phone" : "0466144569",
"email" : "test@test.com",
"country" : "US",
"language" : "en",
"name" : "rockstar"
},
"user" : {
"username" : "rockstar",
"password" : "rockstarpassword",
"consent" : {
"gdpr": "true",
"version": "consent_doc_2009"
}
}
}
问题是,这个有效载荷可以在 4 种不同的情况下发生变化。
1) 整个有效载荷都存在。就像上面的例子一样。
2) organization 丢失的地方。
{
"guid" : "d19b122dc48a4663e33eaa7c83993f7a40ae9329",
"organization" : null
"user" : {
"username" : "rockstar",
"password" : "rockstarpassword",
"consent" : {
"gdpr": "true",
"version": "consent_doc_2009"
}
}
}
3) 缺少user 的地方。
{
"guid" : "d19b122dc48a4663e33eaa7c83993f7a40ae9329",
"organization" : {
"phone" : "0466144569",
"email" : "test@test.com",
"country" : "US",
"language" : "en",
"name" : "rockstar"
},
"user" : null
}
}
4) organization 和 user 都丢失了。
{
"guid" : "d19b122dc48a4663e33eaa7c83993f7a40ae9329",
"organization" : null,
"user" : null
}
我有一个验证这一点的 laravel 请求类。
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class organizationCreation extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'guid' => 'required|string',
'organization.name' => 'required_with:organisation|string|min:3',
'organization.phone' => 'required_with:organisation|regex:/^([0-9\s\-\+\(\)]*)$/|max:20',
'organization.country' => 'required_with:organisation|max:2',
'organization.language' => 'required_with:organisation|max:2',
'organization.email' => 'required_with:organisation|string|max:255',
'user.username' => 'required_with:user|string|max:255',
'user.password' => 'required_with:user',
'user.consent.gdpr' => 'required_with:user|boolean',
'user.consent.version' => 'required_with:user|string|max:255',
];
}
}
我尝试了上述验证,并使用了 required_with,但看起来验证失败了,我不知道如何继续使用具有 4 个不同规则的验证。
我可以通过使用if 检查有效负载来单独验证它们,而不是为其编写代码,但我想一次完成所有这些。
【问题讨论】:
-
在 4 个场景中的哪个场景中验证失败?还是每一个都失败?
标签: laravel validation laravel-request