Wednesday, June 24, 2009

How to validate a hex color in PHP

Validating a hex color code in PHP is easy.

Rules:

Hex colors must start with '#' and have 6 characters.
Hex colors can contain the following letters: [A-F]
Hex colors can contain the following digits: [0-9]

So using pregmatch, the hex validation code is:

if(preg_match('/^#[a-f0-9]{6}$/i', $color)) //hex color is valid
{

}