← Back to all snippets
JAVASCRIPT

Validate Hex Color Code Format

Ensure user input for colors is in a valid hexadecimal format (e.g., #RRGGBB, #RGB) using a concise JavaScript regex pattern, ideal for form validation.

function isValidHexColor(hexColor) {
  const hexRegex = /^#([0-9a-fA-F]{3}){1,2}$/;
  return hexRegex.test(hexColor);
}

// Example usage:
console.log(isValidHexColor('#FFF'));   // true
console.log(isValidHexColor('#FFFFFF')); // true
console.log(isValidHexColor('#abc'));   // true
console.log(isValidHexColor('#abcdef')); // true
console.log(isValidHexColor('FFF'));    // false (missing #)
console.log(isValidHexColor('#FFG'));   // false (invalid character)
console.log(isValidHexColor('#FFFFFFF'));// false (too long)
How it works: This regex `^#([0-9a-fA-F]{3}){1,2}$` validates hex color codes. `^#` asserts the start of the string with a hash. `([0-9a-fA-F]{3})` matches three hexadecimal characters (0-9, a-f, A-F). `{1,2}` means this group can appear once (for `#RGB`) or twice (for `#RRGGBB`). `$` asserts the end of the string, ensuring the entire input matches the pattern.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs