Search code examples
symfonyannotationssymfony-formsassertsymfony-3.2

Symfony: Assert/Length Ignore Whitespace


I have a Model and an attribute $test. I have an annotation for an assert Max-length. But I don't want to count the whitespaces, only the characters. So the text MUST have 40 characters and not a mix of 40 characters with whitespace. Is this possible?

/**
     * @var string
     *
     * @Assert\NotBlank(message = "text.length.error")
     * @Assert\Length(
     *      max = 40,
     *      maxMessage = "Only 40 letters."
     * )
     */
    protected $text;

Solution

  • You can create your own Constraint:

    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(" ", "", $text)) > $constraint->max) {
                $this->context
                    ->buildViolation($constraint->maxMessage)
                    ->addViolation();
            }
        }
    }
    

    YourEntity.php

    use AppBundle\Validator\Constraints\CharacterLength;
    
    /**
     * @var string
     *
     * @CharacterLength(
     *      max = 40,
     *      maxMessage = "Only 40 letters."
     * )
     */
    protected $text;