Skip to content

Instantly share code, notes, and snippets.

@jleehr
Created January 27, 2016 12:34
Show Gist options
  • Save jleehr/0cd88e52874141ba6814 to your computer and use it in GitHub Desktop.
Save jleehr/0cd88e52874141ba6814 to your computer and use it in GitHub Desktop.
Symfony 2 - Custom validator
<?php
namespace AppBundle\Validator\Constraints;
use Symfony\Component\Validator\Constraint;
/**
* @Annotation
*/
class ContainsNumeric extends Constraint
{
public $message = '"%string%" is not a valid value.';
}
<?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();
}
}
}
}
<?php
namespace AppBundle\Dto;
use AppBundle\Validator\Constraints as AppAssert;
class Example {
/**
* @AppAssert\ContainsNumeric
*/
protected $value;
//...
}
@jleehr
Copy link
Author

jleehr commented Jan 27, 2016

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment