Symfony:断言/长度忽略空格

时间:2017-08-25 08:18:21

标签: symfony annotations symfony-forms assert symfony-3.2

我有一个模型和一个属性$test。 我有一个annotation的断言最大长度。但我不想算空白,只计算人物。所以text必须有40个字符,而不是40个字符和空白的混合。这可能吗?

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

2 个答案:

答案 0 :(得分:2)

LongValidator类正在使用mb_strlen函数来确定长度。如果要使用非空白字符的数量进行验证,则需要创建自定义验证器。

注释:

/**
 * @var string
 *
 * @Assert\NotBlank(message = "text.length.error")
 * @Assert\Callback("validate")
 */
protected $text;

验证方法(在同一类中):

public function validate(ExecutionContextInterface $context) {
    if (40 > strlen(str_replace(" ", "", $this->text))) {
        $context->buildViolation('Only 40 letters.')
            ->atPath('text')
            ->addViolation();
    }
}

此metod的参数是Symfony\Component\Validator\Context\ExecutionContextInterface的实例,请务必将其导入文件的顶部。

有关详细信息(例如,如何将验证放入单独的课程中),请检查symfony documentation

答案 1 :(得分:1)

您可以创建自己的约束:

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;