Skip to content
Advertisement

How to access a json child in php respect validation?

I’m trying to validate the following json file but I can’t find the way to access the “Address” child, how should I do it? Everything goes fine until it tries to access the “address” field.

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"
}

Code:

$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()
    ]);

Advertisement

Answer

That is the way to access the child of the 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()
    ]);
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement