简体   繁体   English

Symfony 5.1 没有数据类的表单验证

[英]Symfony 5.1 form validation without data class

It's the first time I build a symfony form on our legacy platform (an old monolith we're refactoring more and more with Symfony 5.1).这是我第一次在我们的遗留平台上构建一个 symfony 表单(一个旧的单体,我们正在用 Symfony 5.1 重构越来越多)。 On other Symfony-only platforms I've managed several times to build forms and validations without problems (3.x, 4.x, 5.x).在其他仅限 Symfony 的平台上,我已经多次成功构建表单和验证,没有问题(3.x、4.x、5.x)。

I stumbled upon a strange behaviour when trying to validate a values length or a valid email address.在尝试验证值长度或有效的电子邮件地址时,我偶然发现了一个奇怪的行为。 When I submit empty fields the isValid() method returns true without the NotBlank constraint.当我提交空字段时,isValid() 方法在没有 NotBlank 约束的情况下返回true For server-side validation I've disabled the client validation.对于服务器端验证,我禁用了客户端验证。

I'm pretty sure that old code does not interfere;我很确定旧代码不会干扰; but the fact is, I'm using a php file to which I'm forwarded by a controller.但事实是,我正在使用一个由控制器转发到的 php 文件。

The $form->isValid() method returns true submitting this field without any data: $form->isValid() 方法返回 true 提交这个没有任何数据的字段:

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('name', TextType::class, [
            'label' => $this->translator->trans('Your name'),
            'constraints' => [
                new Assert\Length([
                    'min' => 3
                ])
            ]
        ]);
    [snip]    
}

The $form->isValid() method returns false when submitting this field empty - which is the desired result:当提交此字段为空时, $form->isValid() 方法返回 false - 这是所需的结果:

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('name', TextType::class, [
            'label' => $this->translator->trans('Your name'),
            'constraints' => [
                new Assert\NotBlank([
                    'message' => $this->translator->trans('This value should not be blank'),
                ]),
                new Assert\Length([
                    'min' => 3,
                    'minMessage' => $this->translator->trans('This value must be at least {{ limit }} characters long')
                ])
            ]
        ]);
    [snip]
}

It seems wrong to me to add a NotBlank constraint - I already check for a minimum length here.添加 NotBlank 约束对我来说似乎是错误的 - 我已经在这里检查了最小长度。 Same for other text fields, also the Email constraint returns true when leaving the field empty.对于其他文本字段,当将字段留空时,电子邮件约束也会返回 true。 I've read the documentation again and again (see https://symfony.com/doc/current/validation.html#constraints-in-form-classes - so it should work), but I don't know what is going wrong here... The fix above was accidentally :).我一遍又一遍地阅读文档(参见https://symfony.com/doc/current/validation.html#constraints-in-form-classes - 所以它应该可以工作),但我不知道发生了什么这里错了......上面的修复是偶然的:)。 Is someone able to explain, why I need the NotBlank-constraint?有人能解释一下,为什么我需要 NotBlank 约束? Or do I miss something...?或者我错过了什么......?

If you go in the code of the Length validator : https://github.com/symfony/symfony/blob/master/src/Symfony/Component/Validator/Constraints/LengthValidator.php如果你进入长度验证器的代码: https : //github.com/symfony/symfony/blob/master/src/Symfony/Component/Validator/Constraints/LengthValidator.php

You can see:你可以看到:

if (null === $value || ('' === $value && $constraint->allowEmptyString)) {
    return;
}

It's considered better that common constraints don't apply to empty values.通用约束不适用于空值被认为更好。 Let's say the user can optionally submit a phone number.假设用户可以选择提交电话号码。 If it's optional, you can't trigger a validation failure on an empty value.如果它是可选的,则不能对空值触发验证失败。 So you're free to forbid the empty value with the NotBlank constraint.因此,您可以使用 NotBlank 约束自由禁止空值。

It makes less sense on the Length constraint of course, but I assume it's done the same way by harmonization.当然,它对 Length 约束的意义不大,但我认为它是通过协调以相同的方式完成的。 What if you want to allow empty value, but want that if a value is submitted, it has a minimal length ?如果您想允许空值,但希望提交的值具有最小长度怎么办? Keeping contraints distinct makes the validation more flexible.保持不同的约束使验证更加灵活。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM