9 追隨者

核心驗證器

Yii 提供了一組常用的核心驗證器,主要位於 yii\validators 命名空間下。您可以不用使用冗長的驗證器類別名稱,而是使用別名來指定使用這些核心驗證器。例如,您可以使用別名 required 來參照 yii\validators\RequiredValidator 類別

public function rules()
{
    return [
        [['email', 'password'], 'required'],
    ];
}

yii\validators\Validator::$builtInValidators 屬性宣告了所有支援的驗證器別名。

在以下內容中,我們將描述每個核心驗證器的主要用法和屬性。

boolean

[
    // checks if "selected" is either 0 or 1, regardless of data type
    ['selected', 'boolean'],

    // checks if "deleted" is of boolean type, either true or false
    ['deleted', 'boolean', 'trueValue' => true, 'falseValue' => false, 'strict' => true],
]

此驗證器檢查輸入值是否為布林值。

  • trueValue:代表 true 的值。預設為 '1'
  • falseValue:代表 false 的值。預設為 '0'
  • strict:輸入值的類型是否應與 trueValuefalseValue 的類型相符。預設為 false

注意:由於透過 HTML 表單提交的資料輸入皆為字串,因此通常應將 strict 屬性保留為 false

captcha

[
    ['verificationCode', 'captcha'],
]

此驗證器通常與 yii\captcha\CaptchaActionyii\captcha\Captcha 一起使用,以確保輸入與 CAPTCHA 小部件顯示的驗證碼相同。

  • caseSensitive:驗證碼的比較是否區分大小寫。預設為 false
  • captchaAction路由 對應於 CAPTCHA action,其呈現 CAPTCHA 圖片。預設為 'site/captcha'
  • skipOnEmpty:如果輸入為空,是否可以跳過驗證。預設為 false,表示輸入為必填。

compare

[
    // validates if the value of "password" attribute equals to that of "password_repeat"
    ['password', 'compare'],

    // same as above but with explicitly specifying the attribute to compare with
    ['password', 'compare', 'compareAttribute' => 'password_repeat'],

    // validates if age is greater than or equal to 30
    ['age', 'compare', 'compareValue' => 30, 'operator' => '>=', 'type' => 'number'],
]

此驗證器將指定的輸入值與另一個值進行比較,並確保它們的關係符合 operator 屬性所指定的關係。

  • compareAttribute:應與之比較值的屬性名稱。當驗證器用於驗證屬性時,此屬性的預設值將為以 _repeat 為後綴的屬性名稱。例如,如果正在驗證的屬性為 password,則此屬性將預設為 password_repeat
  • compareValue:輸入值應與之比較的常數值(或傳回值的閉包)。當同時指定此屬性和 compareAttribute 時,此屬性將優先。
  • operator:比較運算子。預設為 ==,表示檢查輸入值是否等於 compareAttributecompareValue 的值。支援以下運算子
    • ==:檢查兩個值是否相等。比較以非嚴格模式完成。
    • ===:檢查兩個值是否相等。比較以嚴格模式完成。
    • !=:檢查兩個值是否不相等。比較以非嚴格模式完成。
    • !==:檢查兩個值是否不相等。比較以嚴格模式完成。
    • >:檢查正在驗證的值是否大於要比較的值。
    • >=:檢查正在驗證的值是否大於或等於要比較的值。
    • <:檢查正在驗證的值是否小於要比較的值。
    • <=:檢查正在驗證的值是否小於或等於要比較的值。
  • type:預設比較類型為 'string',表示值以位元組為單位進行比較。比較數字時,請確保將 $type 設定為 'number' 以啟用數值比較。

比較日期值

compare 驗證器只能用於比較字串和數字。如果您需要比較日期之類的值,則有兩個選項。對於比較日期與固定值,您可以直接使用 date 驗證器,並指定其 $min$max 屬性。如果您需要比較表單中輸入的兩個日期,例如 fromDatetoDate 欄位,則可以使用 compare 和 date 驗證器的組合,如下所示

['fromDate', 'date', 'timestampAttribute' => 'fromDate'],
['toDate', 'date', 'timestampAttribute' => 'toDate'],
['fromDate', 'compare', 'compareAttribute' => 'toDate', 'operator' => '<', 'enableClientValidation' => false],

由於驗證器按照指定的順序執行,因此這將首先驗證在 fromDatetoDate 中輸入的值是否為有效的日期值,如果是,它們將被轉換為機器可讀的格式。之後,這兩個值將與 compare 驗證器進行比較。用戶端驗證未啟用,因為這僅在伺服器端有效,因為 date 驗證器目前不提供用戶端驗證,因此 $enableClientValidation 也會在 compare 驗證器上設定為 false

date

date 驗證器帶有三個不同的快捷方式

[
    [['from_date', 'to_date'], 'date'],
    [['from_datetime', 'to_datetime'], 'datetime'],
    [['some_time'], 'time'],
]

此驗證器檢查輸入值是否為正確格式的日期、時間或日期時間。或者,它可以將輸入值轉換為 UNIX 時間戳記或其他機器可讀的格式,並將其儲存在透過 timestampAttribute 指定的屬性中。

  • format:要驗證的值應採用的日期/時間格式。這可以是 ICU 手冊 中描述的日期時間模式。或者,這可以是帶有 php: 前綴的字串,表示 PHP Datetime 類別可以識別的格式。請參閱 https://php.dev.org.tw/manual/en/datetime.createfromformat.php 上的支援格式。如果未設定,它將採用 Yii::$app->formatter->dateFormat 的值。有關更多詳細資訊,請參閱 API 文件

  • timestampAttribute:此驗證器可以將從輸入日期/時間轉換而來的 UNIX 時間戳記指派給的屬性名稱。這可以是與正在驗證的屬性相同的屬性。如果是這種情況,則驗證後原始值將被時間戳記值覆蓋。有關使用範例,請參閱 "使用 DatePicker 處理日期輸入"

    自 2.0.4 版起,可以使用 $timestampAttributeFormat$timestampAttributeTimeZone 為此屬性指定格式和時區。

    請注意,當使用 timestampAttribute 時,輸入值將轉換為 unix 時間戳記,根據定義,它是 UTC 時間,因此將執行從 輸入時區 到 UTC 的轉換(自 2.0.39 起,可以透過設定 $defaultTimeZone 來變更此行為)。

  • 自 2.0.4 版起,也可以指定 最小最大 時間戳記。

如果輸入是可選的,您可能還想在日期驗證器之外新增 預設值篩選器,以確保空輸入儲存為 null。否則,您最終可能會在資料庫中得到類似 0000-00-00 的日期,或在日期選擇器的輸入欄位中得到 1970-01-01

[
    [['from_date', 'to_date'], 'default', 'value' => null],
    [['from_date', 'to_date'], 'date'],
],

default

[
    // set "age" to be null if it is empty
    ['age', 'default', 'value' => null],

    // set "country" to be "USA" if it is empty
    ['country', 'default', 'value' => 'USA'],

    // assign "from" and "to" with a date 3 days and 6 days from today, if they are empty
    [['from', 'to'], 'default', 'value' => function ($model, $attribute) {
        return date('Y-m-d', strtotime($attribute === 'to' ? '+3 days' : '+6 days'));
    }],
]

此驗證器不驗證資料。相反地,如果正在驗證的屬性為空,它會將預設值指派給這些屬性。

  • value:預設值或作為回呼的閉包,如果正在驗證的屬性為空,則傳回將指派給這些屬性的預設值。閉包的簽章應如下所示,
function foo($model, $attribute) {
    // ... compute $value ...
    return $value;
}

資訊:如何判斷值是否為空是一個獨立的主題,在 空值 章節中涵蓋。資料庫結構描述中的預設值可以透過模型的 loadDefaultValues() 方法載入。

double

[
    // checks if "salary" is a double number
    ['salary', 'double'],
]

此驗證器檢查輸入值是否為倍精度數字。它等同於 number 驗證器。

  • max:值的上限(包含)。如果未設定,則表示驗證器不檢查上限。
  • min:值的下限(包含)。如果未設定,則表示驗證器不檢查下限。

each

資訊:此驗證器自 2.0.4 版起可用。

[
    // checks if every category ID is an integer
    ['categoryIDs', 'each', 'rule' => ['integer']],
]

此驗證器僅適用於陣列屬性。它驗證陣列的每個元素是否可以透過指定的驗證規則成功驗證。在上述範例中,categoryIDs 屬性必須採用陣列值,並且每個陣列元素都將由 integer 驗證規則驗證。

  • rule:指定驗證規則的陣列。陣列中的第一個元素指定驗證器的類別名稱或別名。陣列中剩餘的名稱-值對用於配置驗證器物件。
  • allowMessageFromRule:是否使用嵌入式驗證規則傳回的錯誤訊息。預設為 true。如果為 false,它將使用 message 作為錯誤訊息。

注意:如果屬性值不是陣列,則會視為驗證失敗,並且將傳回 message 作為錯誤訊息。

email

[
    // checks if "email" is a valid email address
    ['email', 'email'],
]

此驗證器檢查輸入值是否為有效的電子郵件地址。

  • allowName:是否允許電子郵件地址中包含名稱(例如 John Smith <john.smith@example.com>)。預設為 false
  • checkDNS:是否檢查電子郵件的網域是否存在,以及是否具有 A 或 MX 記錄。請注意,即使電子郵件地址實際上有效,此檢查也可能因暫時的 DNS 問題而失敗。預設為 false
  • enableIDN:驗證過程是否應考慮 IDN(國際化網域名稱)。預設為 false。請注意,為了使用 IDN 驗證,您必須安裝並啟用 intl PHP 擴展,否則會擲回例外。

exist

[
    // a1 needs to exist in the column represented by the "a1" attribute
    // i.e. a1 = 1, valid if there is value 1 in column "a1"
    ['a1', 'exist'],
    // equivalent of
    ['a1', 'exist', 'targetAttribute' => 'a1'],
    ['a1', 'exist', 'targetAttribute' => ['a1' => 'a1']],

    // a1 needs to exist, but its value will use a2 to check for the existence
    // i.e. a1 = 2, valid if there is value 2 in column "a2"
    ['a1', 'exist', 'targetAttribute' => 'a2'],
    // equivalent of
    ['a1', 'exist', 'targetAttribute' => ['a1' => 'a2']],
    
    // a2 needs to exist, its value will use a2 to check for the existence, a1 will receive error message
    // i.e. a2 = 2, valid if there is value 2 in column "a2"
    ['a1', 'exist', 'targetAttribute' => ['a2']],
    // equivalent of
    ['a1', 'exist', 'targetAttribute' => ['a2' => 'a2']],

    // a1 and a2 need to exist together, and the first attribute without errors will receive error message
    // i.e. a1 = 3, a2 = 4, valid if there is value 3 in column "a1" and value 4 in column "a2"
    [['a1', 'a2'], 'exist', 'targetAttribute' => ['a1', 'a2']],
    // equivalent of
    [['a1', 'a2'], 'exist', 'targetAttribute' => ['a1' => 'a1', 'a2' => 'a2']],

    // a1 and a2 need to exist together, only a1 will receive error message
    // i.e. a1 = 5, a2 = 6, valid if there is value 5 in column "a1" and value 6 in column "a2"
    ['a1', 'exist', 'targetAttribute' => ['a1', 'a2']],
    // equivalent of
    ['a1', 'exist', 'targetAttribute' => ['a1' => 'a1', 'a2' => 'a2']],

    // a1 needs to exist by checking the existence of both a2 and a3 (using a1 value)
    // i.e. a1 = 7, a2 = 8, valid if there is value 7 in column "a3" and value 8 in column "a2"
    ['a1', 'exist', 'targetAttribute' => ['a2', 'a1' => 'a3']],
    // equivalent of
    ['a1', 'exist', 'targetAttribute' => ['a2' => 'a2', 'a1' => 'a3']],

    // a1 needs to exist. If a1 is an array, then every element of it must exist.
    // i.e. a1 = 9, valid if there is value 9 in column "a1"
    //      a1 = [9, 10], valid if there are values 9 and 10 in column "a1"
    ['a1', 'exist', 'allowArray' => true],
    
    // type_id needs to exist in the column "id" in the table defined in ProductType class
    // i.e. type_id = 1, valid if there is value 1 in column "id" of ProductType's table
    ['type_id', 'exist', 'targetClass' => ProductType::class, 'targetAttribute' => ['type_id' => 'id']],    
    
    // the same as the previous, but using already defined relation "type"
    ['type_id', 'exist', 'targetRelation' => 'type'],
]

此驗證器檢查是否可以在 Active Record 屬性表示的資料表欄中找到輸入值。您可以使用 targetAttribute 來指定 Active Record 屬性,並使用 targetClass 指定對應的 Active Record 類別。如果您未指定它們,它們將採用正在驗證的屬性和模型類別的值。

您可以使用此驗證器來針對單個欄或多個欄進行驗證(即,多個屬性值的組合應存在)。如果同時檢查多個欄(如範例中的 ['a1', 'a2'])並且 skipOnError 設定為 true 時驗證失敗,則只有第一個沒有任何先前錯誤的屬性才會收到新的錯誤訊息。

  • targetClass:應使用的 Active Record 類別名稱,以尋找正在驗證的輸入值。如果未設定,將使用目前正在驗證的模型的類別。
  • targetAttributetargetClass 中應使用的屬性名稱,以驗證輸入值的存在。如果未設定,它將使用目前正在驗證的屬性名稱。您可以使用陣列同時驗證多個欄的存在。陣列值是用於驗證存在的屬性,而陣列鍵是其值要驗證的屬性。如果鍵和值相同,您只需指定值即可。
    假設我們要驗證 ModelA,並將 ModelB 設定為目標類別,則以下 targetAttribute 的配置將被視為
    • null => ModelA 目前正在驗證的屬性值將根據 ModelB 具有相同名稱的屬性的儲存值進行檢查
    • 'a' => ModelA 目前正在驗證的屬性值將根據 ModelB 的屬性 "a" 的儲存值進行檢查
    • ['a'] => ModelA 的屬性 "a" 的值將根據 ModelB 的屬性 "a" 的儲存值進行檢查
    • ['a' => 'a'] => 與上面相同
    • ['a', 'b'] => ModelA 的屬性 "a" 的值將根據 ModelB 的屬性 "a" 的儲存值進行檢查,同時 ModelA 的屬性 "b" 的值將根據 ModelB 的屬性 "b" 的儲存值進行檢查
    • ['a' => 'b'] => ModelA 的屬性 "a" 的值將根據 ModelB 的屬性 "b" 的儲存值進行檢查
  • targetRelation:自 2.0.14 版起,您可以使用方便的屬性 targetRelation,它使用請求關係中的規格覆寫 targetClasstargetAttribute 屬性。
  • filter:要套用於 DB 查詢的其他篩選器,用於檢查輸入值的存在。它可以是字串,也可以是表示其他查詢條件的陣列(請參閱 yii\db\Query::where() 關於查詢條件的格式),或是簽章為 function ($query) 的匿名函式,其中 $query 是您可以修改的函式中的 Query 物件。
  • allowArray:是否允許輸入值為陣列。預設為 false。如果此屬性為 true 且輸入為陣列,則陣列的每個元素都必須存在於目標欄中。請注意,如果您透過將 targetAttribute 設定為陣列來驗證多個欄,則無法將此屬性設定為 true

file

[
    // checks if "primaryImage" is an uploaded image file in PNG, JPG or GIF format.
    // the file size must be less than 1MB
    ['primaryImage', 'file', 'extensions' => ['png', 'jpg', 'gif'], 'maxSize' => 1024*1024],
]

此驗證器檢查輸入是否為有效的上傳檔案。

  • extensions:允許上傳的檔案名稱副檔名列表。它可以是陣列或字串,字串由空格或逗號分隔的檔案副檔名名稱組成(例如 "gif, jpg")。副檔名名稱不區分大小寫。預設為 null,表示允許所有檔案名稱副檔名。
  • mimeTypes:允許上傳的檔案 MIME 類型列表。它可以是陣列或字串,字串由空格或逗號分隔的檔案 MIME 類型組成(例如 "image/jpeg, image/png")。帶有特殊字元 * 的萬用字元遮罩可用於比對 MIME 類型群組。例如,image/* 將通過所有以 image/ 開頭的 MIME 類型(例如 image/jpegimage/png)。MIME 類型名稱不區分大小寫。預設為 null,表示允許所有 MIME 類型。有關更多詳細資訊,請參閱 常見媒體類型
  • minSize:上傳檔案所需的最小位元組數。預設為 null,表示沒有下限。
  • maxSize:上傳檔案允許的最大位元組數。預設為 null,表示沒有上限。
  • maxFiles:給定屬性可以容納的最大檔案數。預設為 1,表示輸入必須是單個上傳檔案。如果大於 1,則輸入必須是由最多 maxFiles 個上傳檔案組成的陣列。
  • checkExtensionByMimeType:是否透過檔案的 MIME 類型檢查檔案副檔名。如果 MIME 類型檢查產生的副檔名與上傳的檔案副檔名不同,則該檔案將被視為無效。預設為 true,表示執行此類檢查。

FileValidatoryii\web\UploadedFile 一起使用。請參閱 上傳檔案 章節,以完整涵蓋有關上傳檔案和執行有關上傳檔案的驗證的內容。

filter

[
    // trim "username" and "email" inputs
    [['username', 'email'], 'filter', 'filter' => 'trim', 'skipOnArray' => true],

    // normalize "phone" input
    ['phone', 'filter', 'filter' => function ($value) {
        // normalize phone input here
        return $value;
    }],
    
    // normalize "phone" using the function "normalizePhone"
    ['phone', 'filter', 'filter' => [$this, 'normalizePhone']],
    
    public function normalizePhone($value) {
        return $value;
    }
]

此驗證器不驗證資料。相反地,它會將篩選器套用於輸入值,並將其指派回正在驗證的屬性。

  • filter:定義篩選器的 PHP 回呼。它可以是全域函式名稱、匿名函式等。函式簽章必須為 function ($value) { return $newValue; }。必須設定此屬性。
  • skipOnArray:如果輸入值為陣列,是否跳過篩選器。預設為 false。請注意,如果篩選器無法處理陣列輸入,則應將此屬性設定為 true。否則,可能會發生某些 PHP 錯誤。

提示:如果您想修剪輸入值,可以直接使用 trim 驗證器。

提示:有許多 PHP 函式具有 filter 回呼預期的簽章。例如,要套用類型轉換(例如使用 intvalboolval 等)以確保屬性的特定類型,您可以直接指定篩選器的函式名稱,而無需將其包裝在閉包中

['property', 'filter', 'filter' => 'boolval'],
['property', 'filter', 'filter' => 'intval'],

image

[
    // checks if "primaryImage" is a valid image with proper size
    ['primaryImage', 'image', 'extensions' => 'png, jpg',
        'minWidth' => 100, 'maxWidth' => 1000,
        'minHeight' => 100, 'maxHeight' => 1000,
    ],
]

此驗證器檢查輸入值是否代表有效的影像檔案。它從 file 驗證器擴展而來,因此繼承其所有屬性。此外,它還支援以下特定於影像驗證目的的其他屬性

  • minWidth:影像的最小寬度。預設為 null,表示沒有下限。
  • maxWidth:影像的最大寬度。預設為 null,表示沒有上限。
  • minHeight:影像的最小高度。預設為 null,表示沒有下限。
  • maxHeight:影像的最大高度。預設為 null,表示沒有上限。

ip

[
    // checks if "ip_address" is a valid IPv4 or IPv6 address
    ['ip_address', 'ip'],

    // checks if "ip_address" is a valid IPv6 address or subnet,
    // value will be expanded to full IPv6 notation.
    ['ip_address', 'ip', 'ipv4' => false, 'subnet' => null, 'expandIPv6' => true],

    // checks if "ip_address" is a valid IPv4 or IPv6 address,
    // allows negation character `!` at the beginning
    ['ip_address', 'ip', 'negation' => true],
]

驗證器檢查屬性值是否為有效的 IPv4/IPv6 位址或子網路。如果啟用了正規化或 IPv6 擴展,它也可能會變更屬性的值。

驗證器具有以下配置選項

  • ipv4:驗證值是否可以為 IPv4 位址。預設為 true
  • ipv6:驗證值是否可以為 IPv6 位址。預設為 true
  • subnet:位址是否可以為帶有 CIDR 子網路的 IP,例如 192.168.10.0/24

    • true - 子網路是必要的,沒有 CIDR 的位址將被拒絕
    • false - 位址不能有 CIDR
    • null - CIDR 是可選的

    預設為 false

  • normalize:是否將 CIDR 前綴與最小長度(IPv4 為 32,IPv6 為 128)新增到沒有它的位址。僅當 subnet 不是 false 時才有效。例如

    • 10.0.1.5 將正規化為 10.0.1.5/32
    • 2008:db0::1 將正規化為 2008:db0::1/128

    預設為 false

  • negation:驗證位址的開頭是否可以帶有否定字元 !。預設為 false
  • expandIPv6:是否將 IPv6 位址擴展為完整表示法格式。例如,2008:db0::1 將擴展為 2008:0db0:0000:0000:0000:0000:0000:0001。預設為 false
  • ranges:允許或禁止的 IPv4 或 IPv6 範圍陣列。

    當陣列為空,或未設定選項時,將允許所有 IP 位址。否則,將依序檢查規則,直到找到第一個符合的規則。當 IP 位址未符合任何規則時,將會被禁止。

    例如: `php [

       'client_ip', 'ip', 'ranges' => [
           '192.168.10.128'
           '!192.168.10.0/24',
           'any' // allows any other IP addresses
       ]
    

    ] ` 在此範例中,除了 192.168.10.0/24 子網路之外,允許所有 IPv4 和 IPv6 位址存取。IPv4 位址 192.168.10.128 也被允許,因為它在限制之前被列出。

  • networks:網路別名陣列,可用於 ranges 中。陣列格式

    • key - 別名名稱
    • value - 字串陣列。字串可以是範圍、IP 位址或另一個別名。字串可以使用 ! 否定(獨立於 negation 選項)。

    預設定義了以下別名

    • *: any
    • any: 0.0.0.0/0, ::/0
    • private: 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, fd00::/8
    • multicast: 224.0.0.0/4, ff00::/8
    • linklocal: 169.254.0.0/16, fe80::/10
    • localhost: 127.0.0.0/8', ::1
    • documentation: 192.0.2.0/24, 198.51.100.0/24, 203.0.113.0/24, 2001:db8::/32
    • system: multicast, linklocal, localhost, documentation

資訊:此驗證器自 2.0.7 版本起可用。

in

[
    // checks if "level" is 1, 2 or 3
    ['level', 'in', 'range' => [1, 2, 3]],
]

此驗證器檢查輸入值是否可以在給定的值列表中找到。

  • range:給定值的列表,輸入值應在其中尋找。
  • strict:輸入值和給定值之間的比較是否應為嚴格模式(類型和值都必須相同)。預設為 false
  • not:是否應反轉驗證結果。預設為 false。當此屬性設定為 true 時,驗證器會檢查輸入值是否「不在」給定的值列表中。
  • allowArray:是否允許輸入值為陣列。當此值為 true 且輸入值為陣列時,陣列中的每個元素都必須在給定的值列表中找到,否則驗證將會失敗。

integer

[
    // checks if "age" is an integer
    ['age', 'integer'],
]

此驗證器檢查輸入值是否為整數。

  • max:值的上限(包含)。如果未設定,則表示驗證器不檢查上限。
  • min:值的下限(包含)。如果未設定,則表示驗證器不檢查下限。

match

[
    // checks if "username" starts with a letter and contains only word characters
    ['username', 'match', 'pattern' => '/^[a-z]\w*$/i']
]

此驗證器檢查輸入值是否符合指定的正規表示式。

  • pattern:輸入值應符合的正規表示式。必須設定此屬性,否則將會拋出例外。
  • not:是否反轉驗證結果。預設為 false,表示只有在輸入值符合模式時,驗證才會成功。如果設定為 true,則只有在輸入值「不」符合模式時,驗證才被視為成功。

number

[
    // checks if "salary" is a number
    ['salary', 'number'],
]

此驗證器檢查輸入值是否為數字。它等同於 double 驗證器。

  • max:值的上限(包含)。如果未設定,則表示驗證器不檢查上限。
  • min:值的下限(包含)。如果未設定,則表示驗證器不檢查下限。

required

[
    // checks if both "username" and "password" are not empty
    [['username', 'password'], 'required'],
]

此驗證器檢查輸入值是否已提供且不為空。

  • requiredValue:輸入應為的期望值。如果未設定,則表示輸入不應為空。
  • strict:驗證值時是否檢查資料類型。預設為 false。當 requiredValue 未設定時,如果此屬性為 true,驗證器將檢查輸入值是否不嚴格等於 null;如果此屬性為 false,驗證器將使用寬鬆規則來判斷值是否為空。當設定了 requiredValue 時,如果此屬性為 true,輸入和 requiredValue 之間的比較也將檢查資料類型。

資訊:如何判斷值是否為空是一個獨立的主題,涵蓋在 空值 章節中。

safe

[
    // marks "description" to be a safe attribute
    ['description', 'safe'],
]

此驗證器不執行資料驗證。相反地,它用於將屬性標記為 安全屬性

string

[
    // checks if "username" is a string whose length is between 4 and 24
    ['username', 'string', 'length' => [4, 24]],
]

此驗證器檢查輸入值是否為具有特定長度的有效字串。

  • length:指定要驗證的輸入字串的長度限制。這可以用以下形式之一指定
    • 整數:字串應有的確切長度;
    • 包含一個元素的陣列:輸入字串的最小長度(例如 [8])。這將覆寫 min
    • 包含兩個元素的陣列:輸入字串的最小和最大長度(例如 [8, 128])。這將覆寫 minmax
  • min:輸入字串的最小長度。如果未設定,則表示沒有最小長度限制。
  • max:輸入字串的最大長度。如果未設定,則表示沒有最大長度限制。
  • encoding:要驗證的輸入字串的編碼。如果未設定,它將使用應用程式的 charset 值,預設為 UTF-8

trim

[
    // trims the white spaces surrounding "username" and "email"
    [['username', 'email'], 'trim'],
]

此驗證器不執行資料驗證。相反地,它會修剪輸入值周圍的空白字元。請注意,如果輸入值是陣列,此驗證器將會忽略它。

unique

[
    // a1 needs to be unique in the column represented by the "a1" attribute
    // i.e. a1 = 1, valid if there is no value 1 in column "a1"
    ['a1', 'unique'],
    // equivalent of
    ['a1', 'unique', 'targetAttribute' => 'a1'],
    ['a1', 'unique', 'targetAttribute' => ['a1' => 'a1']],

    // a1 needs to be unique, but column a2 will be used to check the uniqueness of the a1 value
    // i.e. a1 = 2, valid if there is no value 2 in column "a2"
    ['a1', 'unique', 'targetAttribute' => 'a2'],
    // equivalent of
    ['a1', 'unique', 'targetAttribute' => ['a1' => 'a2']],

    // a1 and a2 need to be unique together, and the first attribute without errors will receive error message
    // i.e. a1 = 3, a2 = 4, valid if there is no value 3 in column "a1" and at the same time no value 4 in column "a2"
    [['a1', 'a2'], 'unique', 'targetAttribute' => ['a1', 'a2']],
    // equivalent of
    [['a1', 'a2'], 'unique', 'targetAttribute' => ['a1' => 'a1', 'a2' => 'a2']],

    // a1 and a2 need to be unique together, only a1 will receive error message
    ['a1', 'unique', 'targetAttribute' => ['a1', 'a2']],

    // a1 needs to be unique by checking the uniqueness of both a2 and a3 (using a1 value)
    // i.e. a1 = 5, a2 = 6, valid if there is no value 5 in column "a3" and at the same time no value 6 in column "a2"
    ['a1', 'unique', 'targetAttribute' => ['a2', 'a1' => 'a3']],
    
    // type_id needs to be unique in the column "id" in the table defined in ProductType class
    // i.e. type_id = 1, valid if there is no value 1 in column "id" of ProductType's table
    ['type_id', 'unique', 'targetClass' => ProductType::class, 'targetAttribute' => 'id'],    
]

此驗證器檢查輸入值在資料表欄位中是否為唯一值。它僅適用於 Active Record 模型屬性。它支援針對單一欄位或多個欄位進行驗證。如果在同時檢查多個欄位(例如範例中的 ['a1', 'a2'])時驗證失敗,且 skipOnError 設定為 true,則只有第一個沒有任何先前錯誤的屬性會收到新的錯誤訊息。

  • targetClass:應使用的 Active Record 類別名稱,以尋找正在驗證的輸入值。如果未設定,將使用目前正在驗證的模型的類別。
  • targetAttributetargetClass 中屬性的名稱,應用於驗證輸入值的唯一性。如果未設定,它將使用目前正在驗證的屬性名稱。您可以使用陣列來同時驗證多個欄位的唯一性。陣列值是將用於驗證唯一性的屬性,而陣列鍵是要驗證其值的屬性。如果鍵和值相同,您可以只指定值。
    假設我們要驗證 ModelA,並將 ModelB 設定為目標類別,則以下 targetAttribute 的配置將被視為
    • null => ModelA 目前正在驗證的屬性值將根據 ModelB 具有相同名稱的屬性的儲存值進行檢查
    • 'a' => ModelA 目前正在驗證的屬性值將根據 ModelB 的屬性 "a" 的儲存值進行檢查
    • ['a'] => ModelA 的屬性 "a" 的值將根據 ModelB 的屬性 "a" 的儲存值進行檢查
    • ['a' => 'a'] => 與上面相同
    • ['a', 'b'] => ModelA 的屬性 "a" 的值將根據 ModelB 的屬性 "a" 的儲存值進行檢查,同時 ModelA 的屬性 "b" 的值將根據 ModelB 的屬性 "b" 的儲存值進行檢查
    • ['a' => 'b'] => ModelA 的屬性 "a" 的值將根據 ModelB 的屬性 "b" 的儲存值進行檢查
  • filter:要應用於 DB 查詢的額外篩選器,用於檢查輸入值的唯一性。這可以是字串,或表示額外查詢條件的陣列(請參閱 yii\db\Query::where() 關於查詢條件的格式),或具有簽名 function ($query) 的匿名函數,其中 $query 是您可以修改的 Query 物件。

url

[
    // checks if "website" is a valid URL. Prepend "http://" to the "website" attribute
    // if it does not have a URI scheme
    ['website', 'url', 'defaultScheme' => 'http'],
]

此驗證器檢查輸入值是否為有效的 URL。

  • validSchemes:指定應視為有效的 URI 協定的陣列。預設為 ['http', 'https'],表示 httphttps URL 都被視為有效。
  • defaultScheme:如果輸入沒有協定部分,則要預先添加到輸入的預設 URI 協定。預設為 null,表示不修改輸入值。
  • enableIDN:驗證器是否應考慮 IDN(國際化域名)。預設為 false。請注意,為了使用 IDN 驗證,您必須安裝並啟用 intl PHP 擴充功能,否則會拋出例外。

注意:驗證器檢查 URL 協定和主機部分是否正確。它「不」檢查 URL 的其餘部分,並且「不」旨在防止 XSS 或任何其他攻擊。請參閱 安全性最佳實務 文章,以瞭解有關開發應用程式時預防威脅的更多資訊。

發現錯字或您認為此頁面需要改進嗎?
在 github 上編輯 !