Skip to content

Instantly share code, notes, and snippets.

@MaximStrutinskiy
Last active September 17, 2017 15:33
Show Gist options
  • Save MaximStrutinskiy/ab508a73a67fc7056905891b8d4d642e to your computer and use it in GitHub Desktop.
Save MaximStrutinskiy/ab508a73a67fc7056905891b8d4d642e to your computer and use it in GitHub Desktop.
Custom symfony constraint.
<?php
namespace MainBundle\Validator\Constraints;
use Symfony\Component\Validator\Constraint;
/** @Annotation */
class CustomLength extends Constraint
{
// Define all annotation parameters;
/**
* @var string
*/
public $minMessage;
/**
* @var string
*/
public $maxMessage;
/**
* @var integer
*/
public $min;
/**
* @var integer
*/
public $max;
/**
* @return string
*
* Use service name: custom_length_validator
*/
public function validatedBy()
{
return 'custom_length';
}
}
<?php
namespace MainBundle\Validator\Constraints;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
class CustomLengthValidator extends ConstraintValidator
{
public $minMessage = "Min data = {{ data }}";
public $maxMessage = "Max data = {{ data }}";
/**
* @param mixed $value
* @param Constraint $constraint
*/
public function validate($value, Constraint $constraint)
{
// Get value from annotation.
$min = $constraint->minMessage;
$max = $constraint->maxMessage;
// Set default value.
if ($min === null) {
$min = $this->minMessage;
}
if ($max === null) {
$max = $this->maxMessage;
}
// Min value.
if (($value < $constraint->min) && ($constraint->min !== null)) {
$this->context->buildViolation($min)
->setParameter('{{ data }}', $constraint->min)
->addViolation();
}
// Max value.
elseif (($value > $constraint->max) && ($constraint->max !== null) ) {
$this->context->buildViolation($max)
->setParameter('{{ data }}', $constraint->max)
->addViolation();
}
}
}
/**
* @ORM\Column(type="string", nullable=false)
* @CustomAssert\CustomLength(
* min = 2,
* max = 5,
* minMessage = "Minimal value = {{ data }}",
* maxMessage = "Maximal value = {{ data }}",
* )
*/
private $test;
services:
custom_length_validator:
class: MainBundle\Validator\Constraints\CustomLengthValidator
tags:
- { name: validator.constraint_validator, alias: custom_length }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment