Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

196
Views
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.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!