php 如何在 symfony2 验证器中允许空值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7519214/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to allow empty values in symfony2 validators
提问by canni
I would like to apply validators on a object properties only when value is not empty ie.
我想仅当值不为空时才对对象属性应用验证器。
Now standard symfony behavior:
现在标准的 symfony 行为:
class Entity
{
/**
* @ORM\Column(type="string", nullable=true)
* @Assert\Email()
*/
protected $email;
(...)
}
that object will not pass validation if an email is null, or empty string, is there a way to tell validator to assert as a valid, an empty value, and validate only if field has data?
如果电子邮件为空或空字符串,该对象将不会通过验证,有没有办法告诉验证器将其断言为有效的空值,并且仅在字段有数据时才进行验证?
PS I know that I can write callback validator, but writting callback for every field just to have "allowEmpty" feature isn't so nice.
PS 我知道我可以编写回调验证器,但是为每个字段编写回调只是为了具有“allowEmpty”功能并不是那么好。
采纳答案by gilden
You must explicitly set 'required' => false
in your FormBuilder
class for all optional fields. Here's a paragraph describing field type options.
您必须'required' => false
在您的FormBuilder
类中为所有可选字段显式设置。这是描述字段类型选项的段落。
Edit.Getting quite a few downvotes. By default allvalidators treat null
values as valid, exceptNotNull
and NotEmpty
. Neither of the two was used in the question. The question is implicitly about how to turn off the client-side required
attribute that is turned on by default.
编辑。获得了相当多的反对票。默认情况下,所有验证器都将null
值视为有效值,除了NotNull
和NotEmpty
。问题中没有使用这两者。问题是关于如何关闭required
默认打开的客户端属性。
回答by David de Boer
Setting the required
option is not the solution:
设置required
选项不是解决方案:
Also note that setting the required option to true will not result in server-side validation to be applied. In other words, if a user submits a blank value for the field (either with an old browser or web service, for example), it will be accepted as a valid value unless you use Symfony's NotBlank or NotNull validation constraint.
另请注意,将 required 选项设置为 true 不会导致应用服务器端验证。换句话说,如果用户为该字段提交一个空白值(例如,使用旧浏览器或 Web 服务),它将被接受为有效值,除非您使用 Symfony 的 NotBlank 或 NotNull 验证约束。
http://symfony.com/doc/current/book/forms.html#field-type-options
http://symfony.com/doc/current/book/forms.html#field-type-options
For my custom validators, I add a
对于我的自定义验证器,我添加了一个
if (null == $value) {
return true;
}
to the isValid()
method. However, I'm not sure what would be the best way for the standard validator classes.
到isValid()
方法。但是,我不确定标准验证器类的最佳方法是什么。
回答by Ahad Ali
if i understand correctly you want server side validation only if value is entered. I am exactly in the same scenario. I want to validate a URL only if the URL is provided. The best way i came across was to write my own custom validation class. You can write a generic custom validation class.
如果我理解正确,您只在输入值时才需要服务器端验证。我完全在同一个场景中。我想仅在提供 URL 时验证 URL。我遇到的最好方法是编写自己的自定义验证类。您可以编写一个通用的自定义验证类。
I followed this link https://symfony-docs-chs.readthedocs.org/en/2.0/cookbook/validation/custom_constraint.htmlexcept for few changes because of symfony's latest version. Here is the implementation
我按照这个链接https://symfony-docs-chs.readthedocs.org/en/2.0/cookbook/validation/custom_constraint.html除了由于 symfony 的最新版本而进行的一些更改。这是实现
Acme\BundleNameBundle\Validator\Constraints\cstmUrl
Acme\BundleNameBundle\Validator\Constraints\cstmUrl
namespace Acme\BundleNameBundle\Validator\Constraints;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\Constraints\Url;
/**
* @Annotation
*/
class CstmUrl extends Url
{
public $message = 'The URL "%string%" is not valid';
}
Acme\BundleNameBundle\Validator\Constraints\cstmUrlValidator
Acme\BundleNameBundle\Validator\Constraints\cstmUrlValidator
namespace Acme\BundleNameBundle\Validator\Constraints;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\Constraints\Url;
use Symfony\Component\Validator\Constraints\UrlValidator;
class CstmUrlValidator extends UrlValidator
{
public function validate($value, Constraint $constraint)
{
if(!$value || empty($value))
return true;
parent::validate($value, $constraint);
}
}
Validtion.yml
验证.yml
Acme\BundleNameBundle\Entity\Student:
Url:
- Acme\BundleNameBundle\Validator\Constraints\CstmUrl: ~
inside Controller just bind the constraint you normally would do
在 Controller 内部只绑定你通常会做的约束
'constraints'=> new CstmUrl(array("message"=>"Invalid url provided"))
I am sure there can be other better ways of doing it, but for now i feel this does the job well.
我相信还有其他更好的方法可以做到这一点,但现在我觉得这很好。
回答by Anton Babushkin
Just in case anyone else comes across this same question. I prefer to personally solve it by adding the following attribute inside my Twig template:
以防万一其他人遇到同样的问题。我更喜欢通过在我的 Twig 模板中添加以下属性来亲自解决它:
{{ form_row(form.<field>, {'required': false}) }}
回答by choomz
Here is the trick I found actually :
这是我实际发现的技巧:
https://github.com/symfony/symfony/issues/5906
https://github.com/symfony/symfony/issues/5906
You need to write a data transformer that does nothing, and then add it to your field. After that, juste call the submit() method with the second param to false.
您需要编写一个什么都不做的数据转换器,然后将其添加到您的字段中。之后,juste 调用 submit() 方法,将第二个参数设置为 false。
Note that it's ok with Symfony 2.3.
请注意,Symfony 2.3 没问题。
回答by David
The Field Type Guessing handle this. http://symfony.com/doc/current/book/forms.html#field-type-guessing
字段类型猜测处理这个。 http://symfony.com/doc/current/book/forms.html#field-type-guessing
It's depends on your form declaration: "The "guessing" is activated when you omit the second argument to the add() method (or if you pass null to it). If you pass an options array as the third argument (done for dueDate above), these options are applied to the guessed field."
这取决于您的表单声明:“当您省略 add() 方法的第二个参数(或者如果您将 null 传递给它)时,“猜测”将被激活。如果您将选项数组作为第三个参数传递(为 DueDate 完成)以上),这些选项应用于猜测的字段。”