1

I created multiple validators using de oficial documentation and all of them works fine, but only when I use separately. In a bundle I defined this:

# Resources/config/validation.ynl
SF\SomeBundle\Entity\SomeEntity:
    properties:
        name:
            - NotBlank: ~
            - SF\UtilsBundle\Validator\Constraints\ContainsAlphanumeric: ~
            - SF\UtilsBundle\Validator\Constraints\MinLength: ~

ContainstAlphanumeric Class validator:

if (!preg_match('/^[a-z\d_]$/i', $value, $matches)) {
    $this->context->addViolation($constraint->message, array('%string%' => $value));
}

MinLength Class validator

$min = 5;
if( strlen($value) < $min )
{
    $this->context->addViolation($constraint->message, array('%string%' => $value, '%min_length%' => $min));
}

So, when I submit a form and the input has the value "q", the validator MinLength returns a length error, but if the same input has the value "qwerty", the validator ContainsAlphanumeric returns an illegal character message.

Any ideas?

Edit:

I changed Resources/config/validation.yml file to use the native SF2 Contraints length validator:

properties:
    name:
        - NotBlank: ~
        - Length: { min: 5, minMessage: "El nombre debe tener almenos {{ limit }} caracteres." }
        - SF\UtilsBundle\Validator\Constraints\ContainsAlphanumeric: ~

And I descover a new behaviour: Some errors are displayed in twig templates with

{{ form_errors(form) }}

and other errors using

{{ form_errors(form.some_field) }}

This is weird!

4

2 回答 2

0

看起来正则表达式是错误的

preg_match('/^[a-z\d_]$/i', $value, $matches)

匹配集合中的任何单个字符[a-z\d_]

注意这里的输出:http ://regex101.com/r/eO8bF0

如果您修复它以便匹配该设置的 0 个或多个字符(因此添加*),它应该可以工作

preg_match('/^[a-z\d_]*$/i', $value, $matches)

http://regex101.com/r/rC4qO3


编辑 回答您的其他问题

{{ form_errors(form) }}

这将显示表单本身的错误,以及冒泡到表单的错误。请参阅有关错误冒泡的文档 http://symfony.com/doc/current/reference/forms/types/text.html#error-bubbling

{{ form_errors(form.some_field) }}

这将显示特定字段的错误。

于 2013-11-04T21:48:31.303 回答
0

对于我没有发现的问题,验证器没有为表单的所有字段返回错误,正如我在询问时所说的那样,一些错误看到了它们,form_errors(form.widget)而另一些则form_errors(form) 解决了我的问题(但我不知道这是否是最好的方式)使用验证服务并将错误返回给树枝。

在行动中:

$form = $this->createCreateForm($entity);
$form->handleRequest($request);

if ($form->isValid())
{
    # Magic code :D
}

return array(
    'entity' => $entity,
    'form'   => $form->createView(),
    'errors' => $this->get('validator')->validate($form) # Here's the magic :D
);

在树枝模板中:

{% if errors is defined %}
    <ul>
        {% for error in errors %}
            <li>
                {{ error.message }}
            </li>
        {% endfor %}
    </ul>
{% endif %}

谢谢你帮助我:D

PD:我决定不使用 error_bubbling 来不修改每个表单字段。

于 2013-11-07T13:50:14.533 回答