JAVASCRIPT
Validate Hex Color Code with Regex
Quickly validate hexadecimal color codes (e.g., #RRGGBB, #RGB, #RGBA, #RRGGBBAA) using a regex pattern in JavaScript for styling applications.
function isValidHexColor(hexColor) {
// Supports #RGB, #RRGGBB, #RGBA, #RRGGBBAA formats
const hexColorRegex = /^#([a-f0-9]{3}|[a-f0-9]{4}|[a-f0-9]{6}|[a-f0-9]{8})$/i;
return hexColorRegex.test(hexColor);
}
// Examples:
// console.log(isValidHexColor("#FFF")); // true
// console.log(isValidHexColor("#000000")); // true
// console.log(isValidHexColor("#F0A5")); // true (RGBA shorthand)
// console.log(isValidHexColor("#12345678")); // true (RRGGBBAA)
// console.log(isValidHexColor("RED")); // false
// console.log(isValidHexColor("#GGGGGG")); // false
// console.log(isValidHexColor("#1234")); // true (4 digit hex is valid)
How it works: This JavaScript snippet uses a regular expression to validate common hexadecimal color code formats. It checks for codes starting with `#` followed by either 3, 4, 6, or 8 hexadecimal characters (0-9, a-f, case-insensitive), covering shorthand RGB, full RGB, shorthand RGBA, and full RGBA notations.