JAVASCRIPT
Validate CSS Hex Color Code Format
Validate CSS hex color codes (e.g., #RRGGBB, #RGB) using a concise JavaScript regex pattern, perfect for front-end form validation.
const isValidHexColor = (hexCode) => {
const hexColorRegex = /^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/;
return hexColorRegex.test(hexCode);
};
// Examples:
// console.log(isValidHexColor("#FFFFFF")); // true
// console.log(isValidHexColor("#abc")); // true
// console.log(isValidHexColor("#12345")); // false (too short)
// console.log(isValidHexColor("FF00EE")); // false (missing #)
// console.log(isValidHexColor("#gg00ff")); // false (invalid characters)
How it works: This JavaScript function `isValidHexColor` checks if a given string is a valid 3-digit or 6-digit hexadecimal color code. The regex `^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$` ensures the string starts with `#` (`^#`), followed by either exactly six hexadecimal characters `[A-Fa-f0-9]{6}` OR (`|`) exactly three hexadecimal characters `[A-Fa-f0-9]{3}`, and ends there (`$`). The `test()` method returns `true` for valid hex codes, `false` otherwise.