Skip to content

Instantly share code, notes, and snippets.

@bjo3rnf
Created November 8, 2012 08:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bjo3rnf/4037470 to your computer and use it in GitHub Desktop.
Save bjo3rnf/4037470 to your computer and use it in GitHub Desktop.
Validator constraint with dependencies
<?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');
}
}
<?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