Symfony表单验证值在数组中(Symfony form validation value is in array)

编程入门 行业动态 更新时间:2024-10-27 15:25:10
Symfony表单验证值在数组中(Symfony form validation value is in array)

目前我正试图弄清楚如何在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.', ))); } }

更多推荐

本文发布于:2023-08-07 21:30:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1466041.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:表单   组中   Symfony   array   validation

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!