Symfony验证:两个数字之间的范围,或一个值

时间:2017-12-07 13:55:30

标签: 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,而忽略了第二个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时才有效。在这种情况下,如何将验证分配给组?

3 个答案:

答案 0 :(得分:4)

您可以将@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;
    }
}
  

根据文档 expression选项是必须返回true以便验证通过的表达式

根据documentation

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

答案 1 :(得分:0)

您可以使用自定义验证约束。要创建一个,您可以参考官方文档:http://symfony.com/doc/3.4/validation/custom_constraint.html

您必须将所有约束放在Validator类的validate函数中。

答案 2 :(得分:0)

从 Symfony 5.1 开始,有一个新的验证器可以检查是否满足多个约束中的至少一个。 AtLeastOneOf

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