控制器中的 Symfony2 Propel 验证(UniqueObject)

Symfony2 Propel validation (UniqueObject) in controller

我的表单验证有问题。表单是手动的,没有使用任何类型。

在我的控制器中我有一个验证:

$form = $request->request->get('form');
$character_name = $form['character_name'];

$character = new Character();
$character->setName($character_name);

$yamlFile = "../src/Game/PlayerBundle/Resources/config/validation.yml";

$validator = Validation::createValidatorBuilder()->addYamlMapping($yamlFile)->getValidator();

$errorList = $validator->validate($character);

if (count($errorList) == 0) {
    $data = array('success' => true);
} else {
    $data = array('success' => false, 'error' => $errorList[0]->getMessage());
}

validation.yml:

Game\PlayerBundle\Model\Character\Character:
  constraints:
    - Propel\PropelBundle\Validator\Constraints\UniqueObject:
        fields: name
        errorPath: name
        message: error.unique.character_name
        groups: select_class
  properties:        
    name:
        - NotBlank:
            message: error.not_blank
            groups: select_class
        - Length:
            min: 3
            max: 32
            minMessage: error.length.{{ limit }}.min.name
            maxMessage: error.length.{{ limit }}.max.name
            groups: select_class
        - Regex:
            pattern: '/^[\w-`][\w-` ]{1,30}[\w-`]$/'
            match: true
            message: error.regex
            groups: select_class

这就是我的全部。验证仍然 returns 没有错误。

Propel\PropelBundle\Validator\Constraints\UniqueObject 只能用于检查 class 属性的唯一性,因此您需要将此约束附加到 class,而不是字符串。

https://github.com/propelorm/PropelBundle/blob/2.0/Validator/Constraints/UniqueObject.php#L75