JAVASCRIPT
Validate Hexadecimal Color Codes (Short and Long)
Validate both 3-digit (#RGB) and 6-digit (#RRGGBB) hexadecimal color codes, with or without the hash, using a simple JavaScript regex pattern.
const hexColorRegex = /^#?([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/;
function isValidHexColor(hex) {
return hexColorRegex.test(hex);
}
// Example usage:
// console.log(isValidHexColor("#FFF")); // true
// console.log(isValidHexColor("00FFCC")); // true
// console.log(isValidHexColor("#ff0099"));// true
// console.log(isValidHexColor("red")); // false
How it works: This regular expression validates hexadecimal color codes. It optionally matches a leading '#' symbol (`#?`) followed by either exactly three hexadecimal characters (`[0-9a-fA-F]{3}`) for short form colors (e.g., #F00) or exactly six hexadecimal characters (`[0-9a-fA-F]{6}`) for long form colors (e.g., #FF0000). The `$` anchor ensures the entire string matches, providing accurate validation for CSS and design inputs.