跳到主要內容

When

編輯此頁面

此約束條件讓您僅在提供的 expression 回傳 true 時,才套用約束條件驗證。請參閱基本用法章節以取得範例。

基本用法

假設您有一個 Discount 類別,其中包含 typevalue 屬性

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) 如果 typepercent,則 value 必須小於或等於 100;B) 如果 typeabsolute,則 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 選項傳遞自訂變數。

constraints

類型array|Constraint

如果 expression 回傳 true,則套用一個或多個約束條件。

groups

類型array | string 預設值null

它定義此約束條件的驗證群組。閱讀更多關於驗證群組的資訊。

payload

類型mixed 預設值null

此選項可用於將任意領域特定的資料附加到約束條件。Validator 元件不會使用已設定的 payload,但其處理完全取決於您。

例如,您可能會想要使用多個錯誤層級,以便根據錯誤的嚴重性,在前端以不同的方式呈現失敗的約束條件。

values

類型array 預設值[]

在 expression 中使用的自訂變數的值。值可以是任何類型(數值、布林值、字串、null 等)。

本作品,包括程式碼範例,皆以創用 CC BY-SA 3.0 授權條款釋出。
目錄
    版本