CssColor
验证一个值是否为有效的 CSS 颜色。底层值在验证之前会被转换为字符串。
适用于 | 属性或方法 |
类 | CssColor |
验证器 | CssColorValidator |
基本用法
在以下示例中, $defaultColor
值必须是以任何有效的 CSS 格式定义的 CSS 颜色 (例如 red
, #369
, hsla(0, 0%, 20%, 0.4)
); $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
正则表达式。允许所有表示带有 alpha 部分的 8 个字符 (除了前导 #
) 并且包含在范围内的 CSS 颜色值:0
到 9
和 A
到 F
(不区分大小写)。
示例:#2F2F2F80
, #2f2f2f80
hex_short_with_alpha
正则表达式。允许所有表示带有 alpha 部分的严格为 4 个字符 (除了前导 #
) 并且包含在范围内的 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)