Saturday, March 12, 2022

[FIXED] Symfony Date Constraint does not allow missing field even though the field is not required

Issue

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,
]);

Solution

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,
]);


Answered By - Beri

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.