PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, March 12, 2022

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

 March 12, 2022     constraints, php, symfony, validation     No comments   

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
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

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

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing