表達式
此約束條件允許您使用表達式進行更複雜、動態的驗證。請參閱基本用法章節以取得範例。另請參閱Callback章節,瞭解提供類似彈性的不同約束條件。
適用於 | 類別或屬性/方法 |
類別 | 表達式 |
驗證器 | ExpressionValidator |
基本用法
假設您有一個名為 BlogPost
的類別,其中包含 category
和 isTechnicalPost
屬性
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
// src/Model/BlogPost.php
namespace App\Model;
use Symfony\Component\Validator\Constraints as Assert;
class BlogPost
{
private string $category;
private bool $isTechnicalPost;
// ...
public function getCategory(): string
{
return $this->category;
}
public function setIsTechnicalPost(bool $isTechnicalPost): void
{
$this->isTechnicalPost = $isTechnicalPost;
}
// ...
}
為了驗證此物件,您有一些特殊需求
- A) 如果
isTechnicalPost
為 true,則category
必須是php
- 或
symfony
;
B) 如果 isTechnicalPost
為 false,則 category
可以是任何值。
實現此目的的一種方法是使用 Expression 約束條件
1 2 3 4 5 6 7 8 9 10 11 12 13
// src/Model/BlogPost.php
namespace App\Model;
use Symfony\Component\Validator\Constraints as Assert;
#[Assert\Expression(
"this.getCategory() in ['php', 'symfony'] or !this.isTechnicalPost()",
message: 'If this is a tech post, the category should be either php or symfony!',
)]
class BlogPost
{
// ...
}
expression 選項是必須傳回 true 才能使驗證通過的表達式。深入瞭解表達式語言語法。
或者,您可以將 negate
選項設定為 false
,以斷言表達式必須傳回 true
才能使驗證失敗。
如需更多關於表達式以及可用的變數資訊,請參閱下方的 expression 選項詳細資訊。
提示
在內部,此表達式驗證器約束條件使用名為 validator.expression_language
的服務來評估表達式。您可以裝飾或擴充該服務以符合您的需求。
選項
expression
type: string
[預設選項]
將被評估的表達式。如果表達式評估為 false 值(使用 ==
,而非 ===
),驗證將會失敗。深入瞭解表達式語言語法。
根據您使用約束條件的方式,您可以在表達式中存取不同的變數
this
:正在驗證的物件(例如 BlogPost 的實例);value
:正在驗證的屬性的值(僅當約束條件直接應用於屬性時才可用);
您也可以在表達式中存取 is_valid()
函數。此函數檢查傳遞給函數的資料是否未引發任何驗證違規。
message
type: string
default: This value is not valid.
當表達式評估為 false 時提供的預設訊息。
您可以在此訊息中使用以下參數
參數 | 描述 |
---|---|
{{ value }} |
目前的(無效)值 |
{{ label }} |
對應的表單欄位標籤 |
payload
type: mixed
default: null
此選項可用於將任意特定領域的資料附加到約束條件。Validator
元件不會使用已設定的 payload
,但其處理完全取決於您。
例如,您可能想要使用多個錯誤層級,以便根據錯誤的嚴重性,在前端以不同的方式呈現失敗的約束條件。
values
type: array
default: []
表達式中使用的自訂變數的值。值可以是任何類型(數值、布林值、字串、null 等)。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
// src/Model/Analysis.php
namespace App\Model;
use Symfony\Component\Validator\Constraints as Assert;
class Analysis
{
#[Assert\Expression(
'value + error_margin < threshold',
values: ['error_margin' => 0.25, 'threshold' => 1.5],
)]
private float $metric;
// ...
}