Home > database >  Symfony Date Constraint does not allow missing field even though the field is not required
Symfony Date Constraint does not allow missing field even though the field is not required

Time:02-03

I am instantiating a constraint collection here to validate my request body for an API I am building. My idea is to validate the birthdate param only for its format, I don't need it to be required. The issue I am having is that, when I do not pass the birthdate in the request body, It throws a missing field error. Basically it treats it as a required field. I don't know why.

$constraint = new Collection([
  'fields' => [
    'birthdate' => [
      new Date(message: 'Please use YYYY-MM-DD format!'),
    ],
  ],
  'allowMissingFields' => false,
  'allowExtraFields' => true,
]);

CodePudding user response:

It didn't cross my mind at first, but following @jean-max comment I figured that you should make a field optional in this case because the default config is required. So yeah this is the answer:

$constraint = new Collection([
  'fields' => [
    'birthdate' => [
      new Optional([
         new Date(message: 'Please use YYYY-MM-DD format!'),
      ]),
    ],
  ],
  'allowMissingFields' => false,
  'allowExtraFields' => true,
]);
  •  Tags:  
  • Related