Created
January 27, 2016 12:34
-
-
Save jleehr/0cd88e52874141ba6814 to your computer and use it in GitHub Desktop.
Symfony 2 - Custom 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 AppBundle\Validator\Constraints; | |
use Symfony\Component\Validator\Constraint; | |
/** | |
* @Annotation | |
*/ | |
class ContainsNumeric extends Constraint | |
{ | |
public $message = '"%string%" is not a valid value.'; | |
} |
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 AppBundle\Validator\Constraints; | |
use Symfony\Component\Validator\Constraint; | |
use Symfony\Component\Validator\ConstraintValidator; | |
use Symfony\Component\Validator\Context\ExecutionContextInterface; | |
class ContainsNumericValidator extends ConstraintValidator | |
{ | |
public function validate($value, Constraint $constraint) | |
{ | |
if ($this->context instanceof ExecutionContextInterface) { | |
if (!preg_match('/([0-9]+(\.[0-9]+)?)/', strval($value), $matches)) { | |
$this->context->buildViolation($constraint->message) | |
->setParameter('%string%', $value) | |
->addViolation(); | |
} | |
} | |
} | |
} |
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 AppBundle\Dto; | |
use AppBundle\Validator\Constraints as AppAssert; | |
class Example { | |
/** | |
* @AppAssert\ContainsNumeric | |
*/ | |
protected $value; | |
//... | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Custom Validator for Symfony 2 (v 2.8)
http://symfony.com/doc/current/cookbook/validation/custom_constraint.html