CssColor
驗證值是否為有效的 CSS 顏色。底層值在驗證前會被轉換為字串。
適用於 | 屬性或方法 |
類別 | CssColor |
驗證器 | CssColorValidator |
基本用法
在以下範例中,$defaultColor
值必須是任何有效 CSS 格式(例如 red
、#369
、hsla(0, 0%, 20%, 0.4)
)中定義的 CSS 顏色;$accentColor
必須是以十六進位格式定義的 CSS 顏色;而 $currentColor
必須是定義為任何具名 CSS 顏色的 CSS 顏色
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
// src/Entity/Bulb.php
namespace App\Entity;
use Symfony\Component\Validator\Constraints as Assert;
class Bulb
{
#[Assert\CssColor]
protected string $defaultColor;
#[Assert\CssColor(
formats: Assert\CssColor::HEX_LONG,
message: 'The accent color must be a 6-character hexadecimal color.',
)]
protected string $accentColor;
#[Assert\CssColor(
formats: [Assert\CssColor::BASIC_NAMED_COLORS, Assert\CssColor::EXTENDED_NAMED_COLORS],
message: 'The color '{{ value }}' is not a valid CSS color name.',
)]
protected string $currentColor;
}
注意
與大多數其他約束條件一樣,null
和空字串被視為有效值。這是為了允許它們成為可選值。如果該值是強制性的,常見的解決方案是將此約束條件與 NotBlank 結合使用。
選項
message
類型:string
預設值:此值不是有效的 CSS 顏色。
如果底層資料不是有效的 CSS 顏色,則會顯示此訊息。
您可以在此訊息中使用以下參數
參數 | 描述 |
---|---|
{{ value }} |
目前(無效)值 |
formats
類型:string
| array
預設情況下,此約束條件會將許多定義 CSS 顏色的方式視為有效。使用 formats
選項來限制允許哪些 CSS 格式。以下是可用的格式(它們也被定義為 PHP 常數;例如 Assert\CssColor::HEX_LONG
)
hex_long
hex_long_with_alpha
hex_short
hex_short_with_alpha
basic_named_colors
extended_named_colors
system_colors
keywords
rgb
rgba
hsl
hsla
hex_long_with_alpha
一個正則表達式。允許所有代表具有 8 個字元(除了前導 #
)且包含在範圍內的 alpha 部分的 CSS 顏色值:0
到 9
和 A
到 F
(不區分大小寫)。
範例:#2F2F2F80
、#2f2f2f80
hex_short_with_alpha
一個正則表達式。允許所有代表具有嚴格為 4 個字元(除了前導 #
)且包含在範圍內的 alpha 部分的 CSS 顏色值:0
到 9
和 A
到 F
(不區分大小寫)。
範例:#CCC8
、#ccc8
system_colors
CSS WG 系統顏色列表中定義的任何有效顏色名稱(不區分大小寫)。
範例:LinkText
、VisitedText
、ActiveText
、ButtonFace
、ButtonText
rgba
一個正則表達式。允許所有代表具有 alpha 部分且遵循 RGB 標記法的 CSS 顏色值,值之間可以有或沒有空格。
範例:rgba(255, 255, 255, 0.3)
、rgba(255,255,255,0.3)
hsla
一個正則表達式。允許所有代表具有 alpha 部分且遵循 HSLA 標記法的 CSS 顏色值,值之間可以有或沒有空格。
範例:hsla(0, 0%, 20%, 0.4)
、hsla(0,0%,20%,0.4)