【问题标题】:symfony validates if another field is specific valuesymfony 验证另一个字段是否是特定值
【发布时间】:2015-03-01 01:22:56
【问题描述】:

如果另一个字段(3) 是选项'a',我正在尝试为一个字段(1) 编写一个验证,如果3 是'b',则另一个字段(2) 是必需的。我该怎么做呢?

编辑: 它适用于实体。我将发布我正在尝试的示例。

/**
*@Assert\Collection(
*fields = { aName = @Assert\NotBlank(),
*           aAmount = @Assert\NotBlank() }
*/
protected $1;

/**
*@Assert\Collection(
*fields = { bName = @Assert\NotBlank(),
*           bAmount = @Assert\NotBlank() }
*/
protected $2;

/**
*@Assert\NotBlank()
*/
protected $3;

如果 $3 == 'a' 我需要 $1,如果 $3 =='b' 我需要 $2。

【问题讨论】:

  • 您使用什么类型的验证?也许你可以展示你的代码
  • 这真的取决于很多因素,需要更多信息。例如,这纯粹是为了表格吗?是为了实体吗?字段是否来自同一实体?等等。您能提供更多信息吗?

标签: php validation symfony


【解决方案1】:

您可以使用验证约束:Expression

例子:

/**
* @Assert\Expression(
 *     "not (this.getThird() == 'a' and this.getFirst() == null)",
 *     message="If third = 'a', first should be not null"
 * )
 */
protected $first;

/**
 * @Assert\Expression(
 *     "not (this.getThird() == 'b' and this.getSecond() == null)",
 *     message="If third = 'b', second should be not null"
 * )
 */
protected $second;

protected $third;

public function getFirst()
{
     return $this->first;   
}

public function getSecond()
{
     return $this->second;   
}

public function getThird()
{
     return $this->third;   
}

【讨论】:

    【解决方案2】:

    【讨论】:

      猜你喜欢
      • 2020-10-23
      • 2011-09-20
      • 1970-01-01
      • 1970-01-01
      • 2015-09-23
      • 2021-06-29
      • 1970-01-01
      • 2012-02-09
      • 1970-01-01
      相关资源
      最近更新 更多