如何为Symfony验证器设置全局字符集


How can I set global charset for Symfony validator?

我在php项目中多次使用Symfony Length Containt。我的Symfony版本是2.5.10

不幸的是,我的字符集是ISO-8859-1,Symfony Length Constraint默认为UTF-8。

好吧,我可以这样更改每个@Assert''Length:

* @Assert'Length(charset="ISO-8859-15")

可能要进行验证工作。

但我想为我的项目全局设置这个字符集,而不是为每个长度断言设置字符集。我该怎么做?

这是一个很好的问题-你当然可以将约束子类化以实现这个

假设2.6默认值:

src/AppBundle/Validator/Constraints/Length.php

<?php
namespace AppBundle'Validator'Constraints;
use Symfony'Component'Validator'Constraints;
/**
 * @Annotation
 *
 * @api
 */
class Length extends Constraints'Length
{
    public $charset = 'ISO-8859-1';
}

然后,在您的实体文件或的任何位置

use Symfony'Component'Validator'Constraints as Assert;
use AppBundle'Validator'Constraints as CustomAssert;
(...)
* @CustomAssert'Length(min=123)

但老实说,我不确定这是否是最好的方式。