Hex color validation with regex

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

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

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

Where $hex_color is the variable which one 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";
}

Leave a Reply

Your email address will not be published. Required fields are marked *