JAVASCRIPT
Validate Hexadecimal Color Codes
Use a JavaScript regular expression to validate both 3-digit (#RGB) and 6-digit (#RRGGBB) hexadecimal color codes for styling and input validation.
const isValidHexColor = (hex) => {
// Regex to match #RGB or #RRGGBB format
// The first group matches # followed by exactly 3 hex chars
// The second group matches # followed by exactly 6 hex chars
const hexColorRegex = /^#([A-Fa-f0-9]{3}){1,2}$/;
return hexColorRegex.test(hex);
};
console.log(isValidHexColor("#FFF")); // true
console.log(isValidHexColor("#00ff99")); // true
console.log(isValidHexColor("#AbC")); // true
console.log(isValidHexColor("#123456")); // true
console.log(isValidHexColor("red")); // false
console.log(isValidHexColor("#FFG")); // false (invalid character 'G')
How it works: The `isValidHexColor` function checks if a string is a valid 3-digit or 6-digit hexadecimal color code. The regex `^#([A-Fa-f0-9]{3}){1,2}$` works by first requiring a leading `#`. Then, `[A-Fa-f0-9]{3}` matches exactly three hexadecimal characters (0-9, A-F, a-f). The `{1,2}` quantifier after the group allows either one occurrence (for #RGB) or two occurrences (for #RRGGBB) of three hex characters. Anchors `^` and `$` ensure the entire string matches the pattern.