project-melody / validator

BSD 3-Clause "New" or "Revised" License
18 stars 5 forks source link

Add key validator #5

Open marcelsud opened 10 years ago

marcelsud commented 10 years ago

Add key validator for validating arrays, such as:

$foo = [
    'name' => 'Marcelo Santos'
];

$validator = v::key("name", v::string()->minLength(10));
$validator->validate($foo); //true

$bar = [
    'name' => 'Marcelo Santos',
    'address' => [
        'street' => 'Lorem ipsum dolor',
        'number' => 123
    ]
];

$validator = v::key("name", v::string()->minLength(10));
$validator->key("address", v::key("street", v::string())->key("number", v::int()));

$validator->validate($bar); //true
jackmakiyama commented 9 years ago

What do you think about a pattern:

$bar = [
    'name' => 'Jack Makiyama',
    'address' => [
        'street' => 'Lorem ipsum dolor',
        'number' => 666
    ]
];

$validator = v::keys([
    "name", v::string()->minLength(10)),
    "address",
        [
            "street" => v::string(),
            "number", v::int()
        ]
]);

$validator->validate($bar); //true
marcelsud commented 9 years ago

@jackmakiyama That would be very nice. We already have a feature called "group validation" which you can pass a set of different rules for different part of the application, such as "registering" for when a user is been registered and "updating" for when a user is beeing edited. But it is not multi dimentional yet:

use Melody\Validation\Validator as v;
use Melody\Validation\ValidationGroups\ValidationGroups;
use Melody\Validation\ValidationGroups\ValidationGroupsFactory;
use Melody\Validation\ValidationGroups\ArrayParserStrategy;

$config = [
    "registering" => [
        "name" => v::string()->minLength(10),
        "username" => v::string()->minLength(8),
        "address" => v::isArray()
    ],
    "updating" => [
        "name" => v::string()->minLength(10)
    ]
];

$strategy = new ArrayParserStrategy($config);
$validator = ValidationGroupsFactory::build($strategy);

$input = [
    "username" => "marcelsud",
    "address" => ""
];

var_dump($validator->validate($input, "registering")); // bool(false)
var_dump($validator->validate($input, "updating")); // bool(true)

I think there is a lot of things to do in order to achieve that level, there is other basic stuff that needs to be fixed before.

marcelsud commented 9 years ago

Also in this group validations the only nodes beeing validated are those inside the $input array, as you may see that the "name" is not passed in the $input and it still is valid. I will open an issue for that.