Skip to content

Conversation

sprain
Copy link
Contributor

@sprain sprain commented May 14, 2013

Q A
Bug fix? no
New feature? yes
BC breaks? no
Deprecations? no
Tests pass? yes
Fixed tickets #3640
License MIT

Due to personal use I extended the DateValidator to handle after and before options. The existing validation of the value being an actual date is still there.

Example:

// only dates within the year 2014 will be valid.
new Assert\Date(array( 
    'after'   => '2013-12-31'
    'before'  => '2015-01-01'
)),

It is possible to change the date format in error messages.
In the example below, an error message for the value '2016-01-01' would look like The date should be before 01.01.2015

new Assert\Date(array( 
    'after'   => '2013-12-31'
    'before'  => '2015-01-01'
    'message' => 'This value is not a valid date',
    'messageAfterDate'  => 'The date should be after {{ after }}',
    'messageBeforeDate' => 'The date should be before {{ before }}',
    'dateFormatMessages' => 'dd.MM.yyyy'
)),

If needed, the DateFormatter can be exchanged completely:

new Assert\Date(array( 
    'after'   => '2013-12-31'
    'messageAfterDate'  => 'The date should be after {{ after }}',
    'dateFormatter' =>  new \IntlDateFormatter('de_DE', \IntlDateFormatter::MEDIUM, \IntlDateFormatter::NONE)
)),

throw new InvalidOptionsException('The option "dateFormatter" must be an instance of \IntlDateFormatter.' . __CLASS__, array('dateFormatter'));
}
} else {
$options['dateFormatter'] = new \IntlDateFormatter('en_US', \IntlDateFormatter::SHORT, \IntlDateFormatter::NONE);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The IntlDateFormatter has nothing to do in the constraint. It is not something you can configure in XML, Yaml or annotations

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since Symfony uses IntlDateFormatter anyways to format dates (e.q. in Symfony\Component\Form\Extension\Core\DataTransformer\BaseDateTimeTransformer) I thought it would be ok to use it here, too. Isn't it?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

constraint classes are meant to be created based on YAML or XML files or as annotations. You cannot provide an IntlDateFormatter there.
Using it could be fine, but it must be created be created the constraint validator, not by the constraint

@stof
Copy link
Member

stof commented May 16, 2013

IMO, it belongs to a separate constraint

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants