phpsymfonysymfony5symfony-validator

How to set option for validation constraint in Symfony globally?


I need to change format for DateTime validation constraint but I want to do it globally for the whole application to not copy-paste it like this:

dateFrom:
  - DateTime
      format: Y-m-d\TH:i:s.vP
dateTo:
  - DateTime
      format: Y-m-d\TH:i:s.vP

(I use yaml config in my application)

Is there any option to do it globally in Symfony 5 application, using DI parameters or some other way?

I didn't find anything about it in official documentation.


Solution

  • You can create a custom constraint extending Symfony\Component\Validator\Constraints\DateTime and set the format there.

    // src/Validator/Constraints/MyDateTime.php
    namespace App\Validator\Constraints;
    
    use Symfony\Component\Validator\Constraints\DateTime as BaseDateTime;
    
    class MyDateTime extends BaseDateTime
    {
        public $format = 'Y-m-d\TH:i:s.vP';
    
        public function validatedBy()
        {
            // use the same validator without this symfony will look for 'App\Validator\Constraints\MyDateTimeValidator' 
            //return static::class.'Validator';
    
            return parent::class.'Validator';
        }
    }
    

    Then you just use custom constraint where needed.

    YAML:

    # config/validator/validation.yaml
    App\Entity\Author:
        properties:
            createdAt:
                - NotBlank: ~
                - App\Validator\Constraints\MyDateTime: ~
    

    Annotations:

    // src/Entity/Author.php
    namespace App\Entity;
    
    use Symfony\Component\Validator\Constraints as Assert;
    use App\Validator\Constraints as MyAssert;
    
    class Author
    {
        /**
         * @Assert\NotBlank
         * @MyAssert\MyDateTime 
         * @var string A "Y-m-d\TH:i:s.vP" formatted value
         */
        protected $createdAt;
    }
    

    So your config would look like this:

    dateFrom:
      - App\Validator\Constraints\MyDateTime: ~
    

    https://symfony.com/doc/current/validation/custom_constraint.html