7

I want to validate a color input field. I want to check whether input value is hex color or not using regex pattern.

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

This is the rule I've made but it gives following error.

preg_match(): No ending delimiter '/' found

Could someone tell what I am doing wrong. Suggestions are appreciated.

Sagar Gautam
  • 9,049
  • 6
  • 53
  • 84

2 Answers2

10

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.

So, try:

'icon_color' => ['required', 'regex:/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/']
wp78de
  • 18,207
  • 7
  • 43
  • 71
2

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

The regular expression itself needs to be surrounded by backslashes (/), similar to Javascript's way of treating strings as regular expressions.

npinti
  • 51,780
  • 5
  • 72
  • 96