When
此約束條件讓您僅在提供的 expression 回傳 true 時,才套用約束條件驗證。請參閱基本用法章節以取得範例。
適用於 | 類別或屬性/方法 |
選項 | |
類別 | When |
驗證器 | WhenValidator |
基本用法
假設您有一個 Discount
類別,其中包含 type
和 value
屬性
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
// src/Model/Discount.php
namespace App\Model;
class Discount
{
private ?string $type;
private ?int $value;
// ...
public function getType(): ?string
{
return $this->type;
}
public function getValue(): ?int
{
return $this->value;
}
}
為了驗證此物件,您有一些需求
A) 如果 type
是 percent
,則 value
必須小於或等於 100;B) 如果 type
是 absolute
,則 value
可以是任何值;C) 無論 type
的值為何,value
都必須大於 0。
達成此目的的一種方法是使用 When 約束條件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
// src/Model/Discount.php
namespace App\Model;
use Symfony\Component\Validator\Constraints as Assert;
class Discount
{
#[Assert\GreaterThan(0)]
#[Assert\When(
expression: 'this.getType() == "percent"',
constraints: [
new Assert\LessThanOrEqual(100, message: 'The value should be between 1 and 100!')
],
)]
private ?int $value;
// ...
}
expression 選項是必須回傳 true 才能觸發附加約束條件驗證的 expression。若要深入瞭解 expression 語言語法,請參閱「Expression 語法」章節。
關於 expression 以及可用的變數的更多資訊,請參閱下方的 expression 選項詳細資訊。
選項
expression
類型:string
以 expression 語言語法撰寫的條件,將會被評估。如果 expression 評估為 falsey 值(即使用 ==
,而非 ===
),則不會觸發約束條件的驗證。
若要深入瞭解 expression 語言語法,請參閱「Expression 語法」章節。
根據您使用約束條件的方式,您可以在 expression 中存取不同的變數
this
- 正在驗證的物件 (例如 Discount 的實例)。
value
- 正在驗證的屬性的值 (僅在約束條件套用至屬性時可用)。
context
- ExecutionContextInterface 物件,提供諸如目前驗證的類別、目前驗證的屬性名稱、違規清單等資訊。
7.2
expression 中的 context
變數是在 Symfony 7.2 中引入的。
當您想要根據 value
執行更複雜的驗證時,可以使用 value
變數
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
// src/Model/Discount.php
namespace App\Model;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\Context\ExecutionContextInterface;
class Discount
{
#[Assert\When(
expression: 'value == "percent"',
constraints: [new Assert\Callback('doComplexValidation')],
)]
private ?string $type;
// ...
public function doComplexValidation(ExecutionContextInterface $context, $payload): void
{
// ...
}
}
您也可以使用 values 選項傳遞自訂變數。
本作品,包括程式碼範例,皆以創用 CC BY-SA 3.0 授權條款釋出。