Created
November 8, 2012 08:01
-
-
Save bjo3rnf/4037470 to your computer and use it in GitHub Desktop.
Validator constraint with dependencies
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace My\Bundle\Validator\Constraint; | |
use Symfony\Component\Validator\Constraint; | |
/** | |
* @Annotation | |
*/ | |
class LaterDateField extends Constraint | |
{ | |
public $message = 'This date has to be later than {{ field }}.'; | |
public $field; | |
public function getDefaultOption() | |
{ | |
return 'field'; | |
} | |
public function getRequiredOptions() | |
{ | |
return array('field'); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace My\Bundle\Validator\Constraint; | |
use Symfony\Component\Validator\ConstraintValidator; | |
use Symfony\Component\Validator\Constraint; | |
use Symfony\Component\Validator\Exception\UnexpectedTypeException; | |
use DateTime; | |
class LaterDateFieldValidator extends ConstraintValidator | |
{ | |
public function isValid($value, Constraint $constraint) | |
{ | |
$earlier = $this->context->getRoot()->get($constraint->field)->getData(); | |
$later = $value; | |
if (null !== $earlier && !$earlier instanceof DateTime) { | |
throw new UnexpectedTypeException($earlier, 'DateTime'); | |
} | |
if (null !== $later && !$later instanceof DateTime) { | |
throw new UnexpectedTypeException($later, 'DateTime'); | |
} | |
if ($earlier > $later) { | |
$this->setMessage($constraint->message, array( | |
'{{ field }}' => $constraint->field, | |
)); | |
return false; | |
} | |
return true; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment