您可以創建自己的約束:
CharacterLength.php
namespace AppBundle\Validator\Constraints;
use Symfony\Component\Validator\Constraint;
/**
* @Annotation
*/
class CharacterLength extends Constraint
{
public $max;
public $maxMessage;
}
CharacterLengthValidator.php
namespace AppBundle\Validator\Constraints;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
class CharacterLengthValidator extends ConstraintValidator
{
/**
* @param string $text
* @param Constraint $constraint
*/
public function validate($text, Constraint $constraint)
{
if (strlen(str_replace(" ", "", $this->text)) > $constraint->max) {
$context
->buildViolation($constraint->maxMessage)
->addViolation();
}
}
}
YourEntity.php
use AppBundle\Validator\Constraints\CharacterLength;
/**
* @var string
*
* @CharacterLength(
* max = 40,
* maxMessage = "Only 40 letters."
*)
*/
protected $text;