我最近开始使用symfony2并推进项目。这不是一个平稳的旅程,但它可以顺利进行。
几天前,我遇到了表单验证问题。我将validation.yml定义为:
Project\MainBundle\Model\User:
properties:
first_name:
- NotBlank: { message: "Please add the user's first name." }
last_name:
- NotBlank: { message: "Please add the user's last name." }
email:
- NotBlank: { message: "Please add the user's email address." }
- Email: { message: "Please use a valid email address." }
password:
- NotBlank: { message: "Please add the user's email address." }
当我提交表单时,除了表单提交一个空白的first_name和last_name时,一切正常。我在调试后发现,问题不在于验证,而在于渲染两个字段的错误。密码和电子邮件错误呈现正常。这是我设置表单的方式。
$builder->add('firstName', 'text');
$builder->add('lastName', 'text');
$builder->add('email', 'text');
$builder->add('password', 'password');
我可以更改我在表单构建器上命名字段的方式,但同时我想遵循symfony2的命名约定(并保留我的数据库命名约定),所以我选择这作为最后的手段。
我希望我能清楚地解释我的问题。任何人都可以为我提供解决方法吗?
答案 0 :(得分:1)
您可以通过getter进行验证。 http://symfony.com/doc/current/validation.html#getters
Project\MainBundle\Model\User:
getter:
firstName:
- NotBlank: { message: "Please add the user's first name." }
lastName:
- NotBlank: { message: "Please add the user's last name." }
email:
- NotBlank: { message: "Please add the user's email address." }
- Email: { message: "Please use a valid email address." }
password:
- NotBlank: { message: "Please add the user's email address." }
答案 1 :(得分:0)
您的问题可能来自于您似乎不尊重YAML语法。
Project\MainBundle\Model\User:
properties:
first_name:
- NotBlank: { message: Please add the user's first name. }
last_name:
- NotBlank: { message: "Please add the user's last name. }
email:
- NotBlank: { message: Please add the user's email address. }
- Email: { message: Please use a valid email address. }
password:
- NotBlank: { message: Please add the user's email address.}