我想验证一个介于 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/