Symfony 验证 : range between two numbers, 或一个值

标签 symfony validation

我想验证一个介于 10 和 20 之间,或 30 和 40 之间或等于 99 的数字。

我可以想象代码与此类似,但它不起作用:

在 Entity\NameOfFile.php 中:

/*
 * @Assert\Range(
 *   min=10,
 *   max=20
 * )
 *
 * @Assert\Range(
 *  min=30,
 *  max=40
 * )
 *
 * @Assert\IdenticalTo(value = 99)
 */
 private $myVariable;

或者类似的东西:

 /*
  * @Assert\Choice({
  *  Range({min = 10, max = 20}),
  *  Range({min = 10, max = 20}), 
  *  99
  * )}
  */
  private $myVariable;

我还添加了最小和最大消息。

在第一个选项中,显然只考虑了第一个 Assert 而忽略了第二个。第二个选项根本不起作用。

Ps: 请,一个没有正则表达式的解决方案

编辑: 按照 M Khalid Juanid 的建议,代码如下所示:

/**
 * @Assert\Expression(
 *     "this.getmyVariable() in 10..20 or this.getmyVariable() in 30..40 or this.getmyVariable() == 99",
 *     message="Your error message", groups{"groupA"}
 * )
*private $myVariable;
 */

  ***
if($appendForm->isValid(array($groupA))
{
***  
}

它工作正常,但仅当验证未分配给 groupA 时。在这种情况下,如何将验证分配给一个组?

最佳答案

您可以使用 @Assert\Expression对于您的多个标准

/**
 * @Assert\Expression(
 *     "this.checkRange()",
 *     message="Your error message"
 * )
 */
class YourEntityName
{
    public function checkRange(){
        if(
            ($this->yourPorperty >= 10 && $this->yourPorperty <= 20)
            || ($this->yourPorperty >= 30 && $this->yourPorperty <= 40)
            || ($this->yourPorperty == 90)
        ){
            return true;
        }

        return false;
    }
}

As per docs The expression option is the expression that must return true in order for validation to pass

根据 documentation 更简单

/**
 * @Assert\Expression(
 *     "this.getYourPorperty() in 10..20 or this.getYourPorperty() in 30..40 or this.getYourPorperty() == 90",
 *     message="Your error message"
 * )
 */

关于Symfony 验证 : range between two numbers, 或一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47696671/

相关文章:

php - 将自定义参数传递给 Symfony2 中的自定义 ValidationConstraint

java - 在业务层返回业务验证结果的首选方法是什么

java - 使用 Jackson 验证列表元素

Symfony2 - 可翻译字段 - 在链配置的命名空间中找不到类 'Gedmo\Translatable\Entity\Translation'

php - Symfony Serializer 不会将对象数组从 camelCase 转换为 snake_case

php - Symfony2 表单组件 - 违反 MVC 和 SRP?

javascript - ColdFusion 表单正则表达式验证出现意外 token 错误

javascript - 如何验证以多个选项卡编写的表单选项卡?

java - 无法通过验证在 JAVA 中运行随机数游戏

php - 遍历学说集合占用太多内存