目前我正试图弄清楚如何在Symfony2的表单构建器上下文中处理TextType字段的表单字段验证。
有一个字段应该用两个可能的值中的一个([email = all],[email = test])手动填写。 它旨在成为一些安全功能,以确保用户明确知道他下一步在做什么。
我想知道是否有验证约束可用于验证字段的输入值以适应两个已知选项之一。 可以[email = all]或[email = test]。 在普通的PHP中,我会这样做
function isValid($value){ $options = array("[email=all]","[email=test]"); return (in_array($value, $options)) ? true : false; }我知道我会构建一个自定义验证约束,但是这可能甚至可以用Symfony标准约束来解决?
提前致谢!
Currently I'm trying to figure out how to handle the form field validation of a TextType field in Symfony2's form builder context.
There is a field that should explicitly be filled manually with one of two possible values ([email=all], [email=test]). It's intended to be some security feature to assure that the user is definitely aware of what he's doing next.
I'm wondering if there is a validation constraint that can be used to validate the field's input value to fit one of the two known options. Either [email=all] or [email=test]. In plain PHP i would do like so
function isValid($value){ $options = array("[email=all]","[email=test]"); return (in_array($value, $options)) ? true : false; }I'm aware that I'd build a custom validation constraint but maybe this could even be solved with Symfony standard constraints?
Thanks in advance!
最满意答案
您可以使用Choice约束。
一个例子:
// src/AppBundle/EntityAuthor.php namespace AppBundle\Entity; use Symfony\Component\Validator\Mapping\ClassMetadata; use Symfony\Component\Validator\Constraints as Assert; class Author { protected $gender; public static function loadValidatorMetadata(ClassMetadata $metadata) { $metadata->addPropertyConstraint('gender', new Assert\Choice(array( 'choices' => array('male', 'female'), 'message' => 'Choose a valid gender.', ))); } }You can use the Choice constraint.
An example:
// src/AppBundle/EntityAuthor.php namespace AppBundle\Entity; use Symfony\Component\Validator\Mapping\ClassMetadata; use Symfony\Component\Validator\Constraints as Assert; class Author { protected $gender; public static function loadValidatorMetadata(ClassMetadata $metadata) { $metadata->addPropertyConstraint('gender', new Assert\Choice(array( 'choices' => array('male', 'female'), 'message' => 'Choose a valid gender.', ))); } }更多推荐
发布评论