Created
April 14, 2012 12:17
-
-
Save netmeansnet/2384021 to your computer and use it in GitHub Desktop.
Symfony2 OverAge Validator
This file contains 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 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; | |
} |
This file contains 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 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; | |
} |
This file contains 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 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