Respect Validation Optional Key

2.2k Views Asked by At

Sometimes users can send some missing key/value pairs. So in that situation I need to validate optional keys if they exists.

User biography is an optional field. If user leaves it empty I don't want it to be posted.

v::key('biography', v::optional(v::stringType()->length(10, 1000)))

Abode code validates if biography is not null or empty, if posted object does not contain biography key it raise exception, because validator expect biography. I couldn't find the way to check "if the key exists continue validation chain"; I can add not existing keys into the posted data before validation but I believe there is a better way to do this in the library.

I am looking a solution that should like this:

v::key('biography', v::keyExist(v::optional(v::stringType()->length(10, 1000))))
2

There are 2 best solutions below

1
On

The documentation of Key states:

Third parameter makes the key presence optional:

v::key('lorem', v::stringType(), false)->validate($dict); // true

That said, if "lorem" does not exists, Validation won't apply the StringType validation.

See: http://respect.github.io/Validation/docs/key.html

2
On

You can use the OneOf validator for your case.

$response = v::key('biography', v::oneOf(
    v::stringType()->length(10, 1000),
    v::nullType()
))->validate($author);

If you try to validate this value:

$author = [];

or this one:

$author = [
    'biography' => 'testtesttest'
];

you'll get true, otherwise if you try to validate this one:

$author = [
    'biography' => 'small'
];

you'll get false (string length is not between 10 and 1000).