针对多个约束验证表单字段

时间:2012-01-12 11:15:57

标签: forms validation symfony

我已经建立了一个注册表单,我想在其中验证字段。 在我的RegistrationFormType我有以下代码:

public function getDefaultOptions(array $options)
    {
        $collectionConstraint = new Collection(array(
            'email' => new Collection(array(
                new NotBlank(),
                new Email(array('message' => 'Invalid email addressadsfa')),
                )),
            'username' => new Email(array('message' => 'arg Invalid email addressadsfa')),
            'code' => new MaxLength(array('limit'=>20)),
            'plainPassword' => new MaxLength(array('limit'=>20)),
        ));

        return array(
            'csrf_protection' => false,
            'validation_constraint' => $collectionConstraint,
        );
    }

问题是:电子邮件验证不起作用。我做错了什么?

1 个答案:

答案 0 :(得分:16)

您不需要将电子邮件条目设为Collection,只需使用简单的数组即可。所以:

public function getDefaultOptions(array $options)
{
    $collectionConstraint = new Collection(array(
        'email' => array(
            new NotBlank(),
            new Email(array('message' => 'Invalid email addressadsfa')),
        ),
        'username' => new Email(array('message' => 'arg Invalid email addressadsfa')),
        'code' => new MaxLength(array('limit'=>20)),
        'plainPassword' => new MaxLength(array('limit'=>20)),
    ));

    return array(
        'csrf_protection' => false,
        'validation_constraint' => $collectionConstraint,
    );
}