Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

iftekhs's avatar
Level 13

How to validate hex color using regex?

Hi, I'm using this to validate that the color is in hex ->

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

but it is giving me this error -> preg_match(): No ending delimiter '^' found

0 likes
7 replies
kokoshneta's avatar

Because you’ve omitted the regex pattern ending delimiter.

Regex patterns must be enclosed in a starting and ending delimiter which must be either identical or a matching pair of brackets, like { and } – they’re there to tell PHP where the pattern ends and the pattern modifiers begin. Your regex starts with the character ^, which PHP interprets as the starting delimiter (even though you intended it to be part of the pattern), and then it expects the same character later on to act as the ending delimiter. You just need to add delimiters before and after your pattern for it to work. Common delimiters are /, #, |, etc.

You could also simplify your pattern by making it case-insensitive – then you wouldn’t have to test for both A-F and a-f:

  $request->validate([
            'color' => 'required|regex:/^#([a-f0-9]{6}|[a-f0-9]{3})$/i',
   ]);
iftekhs's avatar
Level 13

@kokoshneta Yes I kind of actually thought that but I also tried with the delimiter but still doesn't work here is the code -> 'color' => 'required|regex:/^#([a-f0-9]{6}|[a-f0-9]{3})$/i', And now getting -> preg_match(): No ending delimiter '/' found

kokoshneta's avatar
Level 27

@iftekhs Well that’s odd, because (apart from the actual pattern itself), that’s virtually identical to the example given in the validation regex docs.

The docs do say that it may be necessary to use array notation instead of using |, so perhaps the following works?

$request->validate([
	'color' => [
		'required',
		'regex:/^#([a-f0-9]{6}|[a-f0-9]{3})$/i'
	]
]);
1 like
iftekhs's avatar
Level 13

And also I think that was not working because the regex code also had | so I think laravel was having a problem with it reading maybe separating the other part of the regex because of |.

localpathcomp's avatar

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

Yep you would want to use the array syntax.

nexxai's avatar

@localpathcomp Did you revive a year old thread, just to tell someone who already said the problem was solved how to solve their problem?

2 likes

Please or to participate in this conversation.