JAVASCRIPT

Validate Hex Color Codes (RGB/RGBA)

JavaScript regex to validate hex color codes, supporting 3, 6, 4, or 8 digit formats, including optional alpha transparency.

const hexColorRegex = /^#([A-Fa-f0-9]{3}([A-Fa-f0-9]{1})?|[A-Fa-f0-9]{6}([A-Fa-f0-9]{2})?)$/;

function isValidHexColor(hex) {
  return hexColorRegex.test(hex);
}

console.log(isValidHexColor("#FFF"));     // true
console.log(isValidHexColor("#FFFA"));    // true
console.log(isValidHexColor("#FF00FF"));  // true
console.log(isValidHexColor("#FF00FF00")); // true
console.log(isValidHexColor("#GG0"));     // false
console.log(isValidHexColor("FFF"));      // false (missing #)
How it works: This JavaScript regex validates hex color codes, accommodating various common formats. It starts with an `#` and then allows for two main patterns: either three hexadecimal characters followed by an optional fourth (for RGBA shorthand like `#FFFA`), or six hexadecimal characters followed by an optional two (for full RGBA like `#FF00FF00`). This pattern is highly useful for validating color inputs in UI tools or forms where users specify colors.

Need help integrating this into your project?

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

Hire DigitalCodeLabs