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:
JavaScript
x
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.
JavaScript
// 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:
JavaScript
# config/validator/validation.yaml
AppEntityAuthor:
properties:
createdAt:
- NotBlank: ~
- AppValidatorConstraintsMyDateTime: ~
Annotations:
JavaScript
// 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:
JavaScript
dateFrom:
- AppValidatorConstraintsMyDateTime: ~
https://symfony.com/doc/current/validation/custom_constraint.html