Skip to content
Advertisement

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-dTH:i:s.vP
dateTo:
  - DateTime
      format: Y-m-dTH: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.

Advertisement

Answer

You can create a custom constraint extending SymfonyComponentValidatorConstraintsDateTime and set the format there.

// src/Validator/Constraints/MyDateTime.php
namespace AppValidatorConstraints;

use SymfonyComponentValidatorConstraintsDateTime as BaseDateTime;

class MyDateTime extends BaseDateTime
{
    public $format = 'Y-m-dTH:i:s.vP';

    public function validatedBy()
    {
        // use the same validator without this symfony will look for 'AppValidatorConstraintsMyDateTimeValidator' 
        //return static::class.'Validator';

        return parent::class.'Validator';
    }
}

Then you just use custom constraint where needed.

YAML:

# config/validator/validation.yaml
AppEntityAuthor:
    properties:
        createdAt:
            - NotBlank: ~
            - AppValidatorConstraintsMyDateTime: ~

Annotations:

// src/Entity/Author.php
namespace AppEntity;

use SymfonyComponentValidatorConstraints as Assert;
use AppValidatorConstraints as MyAssert;

class Author
{
    /**
     * @AssertNotBlank
     * @MyAssertMyDateTime 
     * @var string A "Y-m-dTH:i:s.vP" formatted value
     */
    protected $createdAt;
}

So your config would look like this:

dateFrom:
  - AppValidatorConstraintsMyDateTime: ~

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

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement