跳到內容

集合

編輯此頁

當底層資料是一個集合(即陣列或實作 TraversableArrayAccess 的物件),但您想要以不同的方式驗證該集合的不同鍵時,會使用此約束條件。例如,您可以使用 Email 約束條件驗證 email 鍵,並使用 Range 約束條件驗證集合的 inventory 鍵。

此約束條件也可以確保某些集合鍵存在,且不存在額外的鍵。

另請參閱

如果您想要驗證集合的所有元素都是唯一的,請使用 Unique 約束條件

適用於 屬性或方法
類別 集合
驗證器 CollectionValidator

基本用法

Collection 約束條件可讓您個別驗證集合的不同鍵。請看以下範例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// src/Entity/Author.php
namespace App\Entity;

class Author
{
    protected array $profileData = [
        'personal_email' => '...',
        'short_bio' => '...',
    ];

    public function setProfileData($key, $value): void
    {
        $this->profileData[$key] = $value;
    }
}

若要驗證 profileData 陣列屬性的 personal_email 元素是否為有效的電子郵件地址,以及 short_bio 元素是否不為空白且長度不超過 100 個字元,您可以使用以下方法:

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/Entity/Author.php
namespace App\Entity;

use Symfony\Component\Validator\Constraints as Assert;

class Author
{
    #[Assert\Collection(
        fields: [
            'personal_email' => new Assert\Email,
            'short_bio' => [
                new Assert\NotBlank,
                new Assert\Length(
                    max: 100,
                    maxMessage: 'Your short bio is too long!'
                )
            ]
        ],
        allowMissingFields: true,
    )]
    protected array $profileData = [
        'personal_email' => '...',
        'short_bio' => '...',
    ];
}

欄位的存在與否

預設情況下,此約束條件驗證的不僅僅是集合中的個別欄位是否通過其指定的約束條件。實際上,如果集合中缺少任何鍵,或者集合中存在任何無法辨識的鍵,則會擲回驗證錯誤。

如果您想要允許集合中缺少鍵,或者如果您想要允許集合中存在「額外」鍵,您可以分別修改 allowMissingFieldsallowExtraFields 選項。在上面的範例中,allowMissingFields 選項設定為 true,表示如果 personal_emailshort_bio 元素從 $personalData 屬性中遺失,則不會發生驗證錯誤。

必要與選填欄位約束條件

集合中欄位的約束條件可以包裝在 RequiredOptional 約束條件中,以控制它們應該始終套用 (Required) 還是僅在欄位存在時套用 (Optional)。

例如,如果您想要要求 profileData 陣列的 personal_email 欄位不為空白且是有效的電子郵件,但 alternate_email 欄位是選填的,但如果提供則必須是有效的電子郵件,您可以執行以下操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// src/Entity/Author.php
namespace App\Entity;

use Symfony\Component\Validator\Constraints as Assert;

class Author
{
    #[Assert\Collection(
        fields: [
            'personal_email' => new Assert\Required([
                new Assert\NotBlank,
                new Assert\Email,
            ]),
            'alternate_email' => new Assert\Optional(
                new Assert\Email
            ),
        ],
    )]
    protected array $profileData = ['personal_email' => 'email@example.com'];
}

即使未將 allowMissingFields 設定為 true,您現在也可以從 profileData 陣列中完全省略 alternate_email 屬性,因為它是 Optional。但是,如果 personal_email 欄位在陣列中不存在,NotBlank 約束條件仍將套用(因為它包裝在 Required 中),並且您將收到約束條件違規。

當您在巢狀約束條件中定義群組時,它們會自動新增至 Collection 約束條件本身,以便可以針對所有巢狀群組進行遍歷。請看以下範例

1
2
3
4
5
6
7
8
use Symfony\Component\Validator\Constraints as Assert;

$constraint = new Assert\Collection([
    'fields' => [
        'name' => new Assert\NotBlank(['groups' => 'basic']),
        'email' => new Assert\NotBlank(['groups' => 'contact']),
    ],
]);

這將產生以下組態

1
2
3
4
5
6
7
8
9
10
11
12
13
$constraint = new Assert\Collection([
    'fields' => [
        'name' => new Assert\Required([
            'constraints' => new Assert\NotBlank(['groups' => 'basic']),
            'groups' => ['basic', 'strict'],
        ]),
        'email' => new Assert\Required([
            "constraints" => new Assert\NotBlank(['groups' => 'contact']),
            'groups' => ['basic', 'strict'],
        ]),
    ],
    'groups' => ['basic', 'strict'],
]);

預設的 allowMissingFields 選項要求所有群組中的欄位。因此,當在 contact 群組中驗證時,$name 可以為空,但鍵仍然是必要的。如果這不是預期的行為,請明確使用 Optional 約束條件,而不是 Required

選項

allowExtraFields

類型boolean 預設值false

如果此選項設定為 false,且底層集合包含一個或多個未包含在 fields 選項中的元素,則會傳回驗證錯誤。如果設定為 true,則額外欄位是允許的。

allowMissingFields

類型boolean 預設值false

如果此選項設定為 false,且 fields 選項中的一個或多個欄位未出現在底層集合中,則會傳回驗證錯誤。如果設定為 true,則允許 fields 選項中的某些欄位未出現在底層集合中。

extraFieldsMessage

類型string 預設值This field was not expected.

如果 allowExtraFields 為 false 且偵測到額外欄位時顯示的訊息。

您可以在此訊息中使用以下參數

參數 描述
{{ field }} 偵測到的額外欄位的鍵

fields

類型array [預設選項]

此選項為必要選項,且為一個關聯陣列,定義集合中的所有鍵,以及針對每個鍵,應針對集合的該元素執行的確切驗證器。

groups

類型array | string 預設值null

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

missingFieldsMessage

類型string 預設值This field is missing.

如果 allowMissingFields 為 false 且底層集合中缺少一個或多個欄位時顯示的訊息。

您可以在此訊息中使用以下參數

參數 描述
{{ field }} fields 中定義的遺失欄位的鍵

payload

類型mixed 預設值null

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

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

本作品,包括程式碼範例,以 Creative Commons BY-SA 3.0 授權條款授權。
目錄
    版本