Hex color validation with regex

Updated:

/

A hex color starts with ‘#’ followed by 6 characters. It contains letters from “A” to “F” and digits “0” to “9”. So an example of a hex color is: #123456.

We can use the php preg_match function for validating a hex color when needed. For validating a hex color, the php expression would be..

preg_match('/^#[a-f0-9]{6}$/i', $hex_color);

Where $hex_color is the variable that contains your color code. So if you have a color code like “#000111”, the checking code will be..

$hex_color = "#000111";
if ( preg_match( '/^#[a-f0-9]{6}$/i', $hex_color ) ) {
    echo "The color code is valid";
} else {
    echo "Invalid color code";
}

Hex colors also have a 3 character shorthand form, like #fff. To accept both forms, use this pattern instead..

preg_match('/^#([a-f0-9]{3}|[a-f0-9]{6})$/i', $hex_color);

And if you are working inside WordPress, there is a built-in sanitize_hex_color() function that does the same job.