跳到主要內容

小於

編輯此頁面

驗證某個值小於另一個值(在選項中定義)。若要強制某個值小於或等於另一個值,請參閱 LessThanOrEqual。若要強制某個值大於另一個值,請參閱 GreaterThan

適用於 屬性或方法
類別 小於
驗證器 LessThanValidator

基本用法

以下約束條件確保

  • Person 的 siblings 數量少於 5
  • age 小於 80
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// src/Entity/Person.php
namespace App\Entity;

use Symfony\Component\Validator\Constraints as Assert;

class Person
{
    #[Assert\LessThan(5)]
    protected int $siblings;

    #[Assert\LessThan(
        value: 80,
    )]
    protected int $age;
}

比較日期

此約束條件可用於比較 DateTime 物件與 DateTime 建構子接受的任何日期字串。例如,您可以像這樣檢查日期是否必須在過去

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

use Symfony\Component\Validator\Constraints as Assert;

class Person
{
    #[Assert\LessThan('today')]
    protected \DateTimeInterface $dateOfBirth;
}

請注意,PHP 將使用伺服器設定的時區來解讀這些日期。如果您想要固定時區,請將其附加到日期字串

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

use Symfony\Component\Validator\Constraints as Assert;

class Person
{
    #[Assert\LessThan('today UTC')]
    protected \DateTimeInterface $dateOfBirth;
}

DateTime 類別也接受相對日期或時間。例如,您可以像這樣檢查某人是否必須至少 18 歲

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

use Symfony\Component\Validator\Constraints as Assert;

class Person
{
    #[Assert\LessThan('-18 years')]
    protected \DateTimeInterface $dateOfBirth;
}

選項

群組

類型array | string 預設值null

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

訊息

類型string 預設值此值應小於 {{ compared_value }}。

如果該值不小於比較值,則會顯示此訊息。

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

參數 描述
{{ compared_value }} 上限
{{ compared_value_type }} 預期的值類型
{{ value }} 目前(無效)的值

酬載

類型mixed 預設值null

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

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

屬性路徑

類型string 預設值null

它定義物件屬性,其值用於進行比較。

例如,如果您想要將某個物件的 $endDate 屬性與同一個物件的 $startDate 屬性進行比較,請在 $endDate 的比較約束條件中使用 propertyPath="startDate"

提示

當使用此選項時,其值在錯誤訊息中以 {{ compared_value_path }} 預留位置提供。雖然不建議將其包含在顯示給終端使用者的錯誤訊息中,但在使用 API 在用戶端進行任何對應邏輯時非常有用。

類型mixed [預設選項]

此選項為必填。它定義比較值。它可以是字串、數字或物件。

本作品(包括程式碼範例)已根據 Creative Commons BY-SA 3.0 授權條款授權。
目錄
    版本