JAVASCRIPT

Validate CSS Hex Color Codes

Quickly validate common CSS hexadecimal color formats (e.g., #FFF, #FFFFFF, FFF, FFFFFF) with a concise regular expression for UI development.

const hexColorPattern = /^#?([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/;

function isValidHexColor(colorString) {
  return hexColorPattern.test(colorString);
}

console.log(isValidHexColor("#FFF")); // true
console.log(isValidHexColor("FFF")); // true
console.log(isValidHexColor("#FF00EE")); // true
console.log(isValidHexColor("FF00EE")); // true
console.log(isValidHexColor("#F0E")); // false (only 3 or 6 hex chars allowed, not 4)
console.log(isValidHexColor("#12345")); // false (not 3 or 6 chars)
console.log(isValidHexColor("red")); // false
How it works: This pattern validates CSS hex color codes. It optionally matches a leading '#' symbol, then requires either exactly three or six hexadecimal characters (0-9, a-f, A-F). This covers both the shorthand (#RGB) and full (#RRGGBB) hex color formats commonly used in web development, ensuring valid color input.

Need help integrating this into your project?

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

Hire DigitalCodeLabs