跳到主要內容

WordCount

編輯此頁面

7.2

WordCount 約束條件在 Symfony 7.2 中引入。

驗證字串(或實作 Stringable PHP 介面的物件)包含指定的字數。在內部,此約束條件使用 IntlBreakIterator 類別根據您的語系計算字數。

適用於 屬性或方法
類別 WordCount
驗證器 WordCountValidator

基本用法

如果您想確保 BlogPostDTO 類別的 content 屬性包含介於 100 到 200 字之間的字數,您可以執行以下操作

1
2
3
4
5
6
7
8
9
10
// src/Entity/BlogPostDTO.php
namespace App\Entity;

use Symfony\Component\Validator\Constraints as Assert;

class BlogPostDTO
{
    #[Assert\WordCount(min: 100, max: 200)]
    protected string $content;
}

選項

最小值

類型: integer 預設值: null

數值必須包含的最少字數。

最大值

類型: integer 預設值: null

數值必須包含的最多字數。

語系

類型: string 預設值: null

用於使用 IntlBreakIterator 類別計算字數的語系。預設值 (null) 表示約束條件使用目前使用者的語系。

群組

類型: array | string 預設值: null

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

最小值訊息

類型: string 預設值: This value is too short. It should contain at least one word.|This value is too short. It should contain at least {{ min }} words.

如果數值未包含至少最少字數,將會顯示此訊息。

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

參數 描述
{{ min }} 最少字數
{{ count }} 實際字數

最大值訊息

類型: string 預設值: This value is too long. It should contain one word.|This value is too long. It should contain {{ max }} words or less.

如果數值包含超過最多字數,將會顯示此訊息。

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

參數 描述
{{ max }} 最多字數
{{ count }} 實際字數

酬載

類型: mixed 預設值: null

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

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

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