十六进制代码验证在 laravel 中不起作用

Hex code validation not working in laravel

我想验证一个颜色输入字段。我想使用正则表达式模式检查输入值是否为十六进制颜色。

'icon_color' => 'required|regex:^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$',

这是我制定的规则,但出现以下错误。

preg_match(): No ending delimiter '/' found

谁能告诉我我做错了什么。欢迎提出建议。

这个:icon_color' => 'required|regex:^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$',需要变成这个:'icon_color' => 'required|regex:/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/'

正则表达式本身需要用反斜杠包围(/),类似于Javascript将字符串视为正则表达式的方式。

When using the regex / not_regex patterns, it may be necessary to specify rules in an array instead of using pipe delimiters, especially if the regular expression contains a pipe character. See the docs.

所以,尝试:

'icon_color' => ['required', 'regex:/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/']