0

In Slim3 framework's Respect Validation, I am trying to add validation on child object.

$childObjValidationArr = array(
  'param1' => v::regex("/^[A-Za-z0-9]{1}[A-Za-z0-9.$#-@]{1,19}$/"),
  'param2' => v::date('Y-m-d'),
  'param3' => v::intVal()->not(v::negative())
);

It works fine if child object is not optional.

$mainObjectValidators = array(
  'id' => $intPositive,
  'childObj' => $childObjValidationArr
);

But not working when child is optional (null allowed).

$mainObjectValidators = array(
  'id' => $intPositive,
  'childObj' => v::optional($childObjValidationArr)
);

Any way to add optional validation for child object with Respect?

Below is the error when attempted above

PHP Fatal error: Uncaught TypeError: Argument 1 passed to Respect\Validation\Rules\Optional::__construct() must implement interface Respect\Validation\Validatable, null given

Anup B
  • 87
  • 7

1 Answers1

0

I have tried below

$childObjectValidator = v::when(v::notOptional(), 
v::attribute('pCode', $codeRegex)
->attribute('pDate', v::date('Y-m-d'))
->attribute('pId', $intPositiveZeroAllowed));

But then KeySet worked for me when combined it with when

$pValidator = v::keySet(
  v::key('pCode', $codeRegex),
  v::key('pDate, v::date('Y-m-d')),
  v::key('pId', $intPositiveZeroAllowed)
);

$childObjectValidator = v::when(v::notOptional(), $pValidator, v::nullType());

and main validator looks like below

$mainObjectValidators = array(
  'id' => $intPositive,
  'childObj' => $childObjectValidator
);
Anup B
  • 87
  • 7