Skip to content

Instantly share code, notes, and snippets.

@netmeansnet
Created April 14, 2012 12:17
Show Gist options
  • Save netmeansnet/2384021 to your computer and use it in GitHub Desktop.
Save netmeansnet/2384021 to your computer and use it in GitHub Desktop.
Symfony2 OverAge Validator
<?php
namespace Acme\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Nmn\Validator\Constraints as NmnAssert;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
/**
* @ORM\Entity
* @ORM\Table(name="my_table_name")
*/
class MyEntity
{
/**
* @ORM\Column(type="datetime")
* @Assert\DateTime()
* @NmnAssert\OverAge(age="18")
*/
protected $dateOfBirth;
}
<?php
namespace Nmn\Validator\Constraints;
use Symfony\Component\Validator\Constraint;
/**
* @Annotation
*
*/
class OverAge extends Constraint
{
public $message = 'The minimum age required is {{ age }} years';
public $age = 18;
}
<?php
namespace Nmn\Validator\Constraints;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\ConstraintDefinitionException;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
/**
*
* @api
*/
class OverAgeValidator extends ConstraintValidator
{
public function isValid($value, Constraint $constraint)
{
if (!$value instanceof \DateTime) {
throw new UnexpectedTypeException($value, 'DateTime');
}
$minimumDate = new \DateTime(date('Y-m-d'));
$minimumDate->sub(new \DateInterval('P'.$constraint->age.'Y'));
$interval = $minimumDate->diff($value);
$dayDiff = $interval->format('%R%d');
if ($dayDiff > 0) {
$this->setMessage($constraint->message, array('{{ age }}' => $constraint->age));
return false;
}
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment