在数据转换之前应用验证 [英] Apply validation before Data Transform

查看:159
本文介绍了在数据转换之前应用验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将从提交的用户数据获得的文本字段转换为Symfony2中的对象。我使用DataTransformer来做到这一点。当我使用诸如'NotEmpty'或'NotNull'之类的内置校验器或以标准方式构建的任何自定义验证器时,Symfony2会将我的特定对象传递给它们,但我想在将其转换为对象之前验证此文本字段。我该怎么办? (如果我的英文不是那么好的话,也可以)

解决方案

验证总是在反向转换的数据上完成。 b
$ b

在转换发生之前添加验证规则的最佳方法是在 FormEvents :: PRE_SUBMIT 中使用事件侦听器或订阅者。 p>

您将获得原始数据。在这里应用您的验证逻辑,然后使用 $ event-> getForm() - > get('xxxx') - > addError()相关的字段。



有关事件订阅者/听众的更多信息:

http://symfony.com/doc/current/components/form/form_events.html#event-listeners
http://symfony.com /doc/current/components/form/form_events.html#event-subscribers


I want to transform a text field that I got from submitted user data to an Object in Symfony2. I used DataTransformer in order to do this. When I use built-in validators like 'NotEmpty' or 'NotNull' or any custom validators that built in standard way Symfony2 passes my specific object to them but I want to validate this text field before converting it to object. What should I do? (sry if my English is not so good)

解决方案

Validation are always done on the reverse transformed data.

The best way to add validation rule before the transformation occurred is to use an event listener or subscriber on FormEvents::PRE_SUBMIT.

You'll get the raw data. Just apply your validation logic here then use the $event->getForm()->get('xxxx')->addError() method to add errors on the corresponding field.

More informations on event subscribers / listeners :

http://symfony.com/doc/current/components/form/form_events.html#event-listeners http://symfony.com/doc/current/components/form/form_events.html#event-subscribers

这篇关于在数据转换之前应用验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆