Validate a hex color code in JavaScript
Intermediate · 3 min read
Hex color codes like #3055d8 are how most web pages write colors. Theme editors, design tools and "pick your brand color" fields all accept them, and they need to check the code before saving it. A wrong code either breaks the page style or is silently ignored by the browser.
In this tutorial you will write isHexColour, which accepts all four lengths CSS allows: 3, 4, 6 and 8 digits. Then you will expand the short forms and read the red, green, blue and transparency values out as numbers. You need to know /.../.test(), ^, $ and what hex digits are (0 to 9 and a to f). The rest is explained as we go.
How a hex color is built
A six-digit color is three pairs of hex digits: red, green and blue. Each pair goes from 00 (none) to ff (full, which is 255):
#3055d8
30 = red (48)
55 = green (85)
d8 = blue (216)
There are three more forms:
- 3 digits is a shorthand where each digit is doubled:
#f00means#ff0000, pure red. - 8 digits adds a fourth pair for alpha, the transparency.
ffis fully solid and80is about half see-through. - 4 digits is the shorthand of the 8-digit form:
#f008means#ff000088.
Five and seven digits are not valid.
Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.
17 Is the value a hex colour?
fairCheck whether a string is a hex colour. CSS allows three, four, six and eight digits, not only six.
Stuck? Three hints, smallest first
- 1. Three digits is shorthand:
#f00means#ff0000. - 2. Four and eight digits include an alpha channel, and both are valid modern CSS.
- 3. Use alternation on the length rather than
{3,8}, which would allow 5 and 7.
Step 1: the wrong turn with {3,8}
{3,8} means "between 3 and 8 of the thing before". It looks like exactly what we need:
const loose = /^#[0-9a-f]{3,8}$/i;
console.log(loose.test('#fff')); // true
console.log(loose.test('#3055d8')); // true
console.log(loose.test('#12345')); // true, but 5 digits is not a color
A range quantifier allows every length in between, including 5 and 7.
Step 2: list the exact lengths
Use | ("or") to list each allowed length, inside a group so the # and the anchors apply to all of them. The i flag accepts capitals:
const HEX_COLOUR = /^#([0-9a-f]{3}|[0-9a-f]{4}|[0-9a-f]{6}|[0-9a-f]{8})$/i;
const isHexColour = (value) => typeof value === 'string' && HEX_COLOUR.test(value);
console.log(isHexColour('#FFF')); // true
console.log(isHexColour('#3055d8ff')); // true
console.log(isHexColour('#12345')); // false
console.log(isHexColour('#1234567')); // false
console.log(isHexColour('3055d8')); // false: no #
console.log(isHexColour('#gggggg')); // false
Step 3: expand the shorthand
To work with any color the same way, turn the 3- and 4-digit forms into their long versions. Spread the digits into an array, double each one, and join them back:
const HEX_COLOUR = /^#([0-9a-f]{3}|[0-9a-f]{4}|[0-9a-f]{6}|[0-9a-f]{8})$/i;
const isHexColour = (value) => typeof value === 'string' && HEX_COLOUR.test(value);
function expand(colour) {
if (!isHexColour(colour)) return null;
const d = colour.slice(1);
if (d.length === 3 || d.length === 4) {
return '#' + [...d].map((c) => c + c).join('').toLowerCase();
}
return '#' + d.toLowerCase();
}
console.log(expand('#f00')); // '#ff0000'
console.log(expand('#ffff')); // '#ffffffff'
console.log(expand('#3055D8')); // '#3055d8'
console.log(expand('#12345')); // null
slice(1) drops the #. Lower-casing every result means two spellings of the same color give the same string.
Step 4: read the channels as numbers
Each channel is one pair of digits. /../g matches any two characters, again and again, so match splits the string into pairs. Then parseInt(pair, 16) turns each pair into a number from 0 to 255:
console.log('3055d8'.match(/../g)); // [ '30', '55', 'd8' ]
console.log(Number.parseInt('d8', 16)); // 216
A six-digit color has no alpha pair, so the answer treats a missing alpha as 255, fully solid:
function channels(full) {
const pairs = full.slice(1).match(/../g).map((p) => Number.parseInt(p, 16));
return { r: pairs[0], g: pairs[1], b: pairs[2], a: pairs[3] ?? 255 };
}
console.log(channels('#ff0000')); // { r: 255, g: 0, b: 0, a: 255 }
console.log(channels('#3055d880')); // { r: 48, g: 85, b: 216, a: 128 }
In the full answer, channels calls expand first, so it works on the short forms too.
The full solution
The panel checks a list of colors, expands each valid one, and prints the channels for a solid red and a half-transparent blue. Press Run and look at the 5- and 7-digit rows.
// 3, 4, 6 or 8 digits. Alternation on the lengths, because {3,8} would also
// allow 5 and 7, which are not valid.
const HEX_COLOUR = /^#([0-9a-f]{3}|[0-9a-f]{4}|[0-9a-f]{6}|[0-9a-f]{8})$/i;
const isHexColour = (value) => typeof value === 'string' && HEX_COLOUR.test(value);
// Expanding the shorthand, which is what a browser does internally.
function expand(colour) {
if (!isHexColour(colour)) return null;
const d = colour.slice(1);
if (d.length === 3 || d.length === 4) {
return '#' + [...d].map((c) => c + c).join('').toLowerCase();
}
return '#' + d.toLowerCase();
}
// The channels as numbers, alpha included.
function channels(colour) {
const full = expand(colour);
if (!full) return null;
const d = full.slice(1);
const pairs = d.match(/../g).map((p) => Number.parseInt(p, 16));
return { r: pairs[0], g: pairs[1], b: pairs[2], a: pairs[3] ?? 255 };
}
const cases = ['#fff', '#FFF', '#f00', '#ffff', '#3055d8', '#3055D8', '#3055d8ff',
'3055d8', '#12345', '#1234567', '#gggggg', '#', '', '#3055d8 '];
for (const c of cases) {
console.log(JSON.stringify(c).padEnd(12), 'valid:', String(isHexColour(c)).padEnd(6), 'expanded:', expand(c));
}
console.log('channels of #f00 :', channels('#f00'));
console.log('channels of #3055d880:', channels('#3055d880'));
Output
23 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 23 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('three digits pass', isHexColour('#fff'), true);
test('upper case passes', isHexColour('#FFF'), true);
test('four digits pass, with alpha', isHexColour('#ffff'), true);
test('six digits pass', isHexColour('#3055d8'), true);
test('eight digits pass', isHexColour('#3055d8ff'), true);
test('five digits are not valid', isHexColour('#12345'), false);
test('nor are seven', isHexColour('#1234567'), false);
test('the hash is required', isHexColour('3055d8'), false);
test('non-hex letters are refused', isHexColour('#gggggg'), false);
test('the hash alone is refused', isHexColour('#'), false);
test('an empty string is refused', isHexColour(''), false);
test('a trailing space is refused', isHexColour('#3055d8 '), false);
test('three-digit shorthand expands by doubling', expand('#f00'), '#ff0000');
test('and #fff becomes white', expand('#fff'), '#ffffff');
test('four-digit shorthand expands too', expand('#ffff'), '#ffffffff');
test('a six-digit colour is only lower-cased', expand('#3055D8'), '#3055d8');
test('an invalid colour expands to null', expand('#12345'), null);
test('the channels of red', channels('#f00'), { r: 255, g: 0, b: 0, a: 255 });
test('alpha defaults to fully opaque', channels('#3055d8').a, 255);
test('and is read when present', channels('#3055d880').a, 128);
test('shorthand and long form give the same channels', channels('#f00'), channels('#ff0000'));
test('white is all 255', channels('#fff'), { r: 255, g: 255, b: 255, a: 255 });
test('black is all 0', channels('#000'), { r: 0, g: 0, b: 0, a: 255 });
Alternating on the exact lengths, {3}|{4}|{6}|{8}, rather than writing {3,8}, is what makes this correct: five and seven digits are not valid CSS, and the assertions check both are refused. It is a small thing that a range quantifier gets silently wrong.
Four and eight digit forms are worth knowing about. #3055d880 is the same blue at 50% opacity, and the shorthand expands by doubling each digit — which is why #f00 and #ff0000 produce identical channels, as the assertion confirms.
If you are parsing colours in earnest rather than validating a field, note that CSS also has rgb(), hsl(), oklch(), named colours and color-mix(). A hex pattern covers one notation out of many.
Common mistakes
- Using
{3,8}. It accepts 5 and 7 digits. List the four exact lengths with|. - Forgetting the group around the
|. Without it,^#[0-9a-f]{3}|[0-9a-f]{6}$means "starts with # and three digits" or "ends with six digits", which matches far too much. - Expanding by repeating the whole string.
#f00becomes#ff0000by doubling each digit, not#f00f00.
Try it yourself
- Write
toRgb(colour)that returns a string like'rgb(255, 0, 0)'usingchannels. - Make the
#optional, so'3055d8'also passes. - Write
isOpaque(colour)that returnstruewhen the alpha is 255.