如何在php方面验证中访问json子级



我正在尝试验证以下json文件,但我找不到访问"地址";孩子,我该怎么做?一切都很好,直到它试图访问";地址";领域

Json:

{
"first_name": "Test",
"last_name": "Test",
"email": "test@gmail.com",
"mobile_phone": 123456789,
"address": {
"country": "Test",
"postal_code": "Test",
"city": "Test",
"street": "Test",
"number": "Test",
"floor": "Test",
"door": "Test"
},
"password": "Test",
"birth_date": "2005-12-30"
}

代码:

$data = $this->validator->validate($request, [
"first_name" => v::stringVal()->notEmpty(),
"last_name" => v::stringVal()->notEmpty(),
"email" => v::notEmpty()->email(),
"mobile_phone" => v::intVal()->notEmpty(),
"address" =>[
"country" => v::stringVal()->notEmpty(),
"postal_code" => v::stringVal()->notEmpty(),
"city" => v::stringVal()->notEmpty(),
"street" => v::stringVal()->notEmpty(),
"number" => v::stringVal()->notEmpty(),
"floor" => v::stringVal()->notEmpty(),
"door" => v::stringVal()->notEmpty(),
],
"password" => v::base64()->notEmpty(),
"birth_date" => v::date()->notEmpty()
]);

看起来您正在使用Respect\Validation\Validator。我们可以使用链式验证和Key函数来验证子数组,如文档所示。

$data = [
'parentKey' => [
'field1' => 'value1',
'field2' => 'value2'
'field3' => true,
]
];

使用下一个规则组合,我们可以验证子密钥。

v::key(
'parentKey',
v::key('field1', v::stringType())
->key('field2', v::stringType())
->key('field3', v::boolType())
)
->assert($data); // You can also use check() or validate()

应用于您的数据,验证可能如下所示:

use RespectValidationValidator as v;
$json = json_decode('{
"first_name": "Test",
"last_name": "Test",
"email": "test@gmail.com",
"mobile_phone": 123456789,
"address": {
"country": "Test",
"postal_code": "Test",
"city": "Test",
"street": "Test",
"number": "Test",
"floor": "Test",
"door": "Test"
},
"password": "Test",
"birth_date": "2005-12-30"
}', true);

v::create()
->key('first_name', v::stringType()->length(1, 32))
->key('last_name', v::stringVal()->notEmpty())
//->..
->key('address',
v::key('country', v::stringType()->length(1, 32))
->key('postal_code', v::stringType()->length(1, 32))
->key('city', v::stringType()->length(1, 32))
//->..
)
->key('password', v::stringVal()->notEmpty())
->key('birth_date', v::stringVal()->notEmpty())
->assert($json); // You can also use check() or validate()

这是访问json:的子级的方法

$this->validator->validate($request, [
"first_name" => v::stringVal()->notEmpty(),
"last_name" => v::stringVal()->notEmpty(),
"email" => v::notEmpty()->email(),
"mobile_phone" => v::intVal()->notEmpty(),
"address" => v::notEmpty()
->key("country", v::stringVal()->notEmpty())->key("postal_code", v::stringVal())->key("city", v::stringVal()->notEmpty())->key("street", v::stringVal()->notEmpty())->key("number", v::stringVal())->key("floor", v::stringVal())->key("door", v::stringVal()),
"password" => v::base64()->notEmpty(),
"birth_date" => v::date('d/m/Y')->notEmpty()
]);

相关内容

  • 没有找到相关文章

最新更新