3

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))))
Johannes
  • 64,305
  • 18
  • 73
  • 130
RockOnGom
  • 3,893
  • 6
  • 35
  • 53

2 Answers2

2

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

  • 1
    Yes if Lorem does not exist it throws error, but I don’t want it to raise error when it not exists. I want validation to validate if it exists other wise continue rest validation chains – RockOnGom May 19 '18 at 15:41
0

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).

Davide Pastore
  • 8,678
  • 10
  • 39
  • 53
  • I realize this is a pretty old question and answer, but the above does not work for me. I'm still seeing an exception thrown saying the key must be present. – Ethan Hohensee Jan 11 '21 at 21:48
  • 1
    I figured it out. v::key has an optional third argument called `mandatory` that can be set to false. This allowed me to validate the value if present, but ignore it and not raise an error if it's missing. – Ethan Hohensee Jan 11 '21 at 21:54