Hello everyone!

We have been investing plenty of personal time and energy for many years to share our knowledge with you all. However, we now need your help to keep this blog running. All you have to do is just click one of the adverts on the site, otherwise it will sadly be taken down due to hosting etc. costs. Thank you.

You can use example below to create a constraint validator, set it as a service and inject dependencies into it.


Constraint


namespace Application\TestBundle\Validator\Constraints;

use Symfony\Component\Validator\Constraint;

/**
* @Annotation
*/
class Coordinate extends Constraint
{
public function getTargets()
{
return self::CLASS_CONSTRAINT;
}

public function validatedBy()
{
return 'application_coordinate_validator';
}
}

namespace Application\TestBundle\Validator\Constraints;

use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;

class CoordinateValidator extends ConstraintValidator
{
private $postcodesApiUri;

public function __construct($postcodesApiUri)
{
$this->postcodesApiUri = $postcodesApiUri;
}

public function validate($property, Constraint $constraint)
{
// Do something ...
}
}

Service


services:
application.validator.coordinate_validator:
class: Application\TestBundle\Validator\Constraints\CoordinateValidator
arguments:
- "http://api.myendpoint.com/postcodes/"
tags:
-
name: validator.constraint_validator
alias: application_coordinate_validator
# OR
# tags:
# - { name: validator.constraint_validator, alias: application_coordinate_validator }