JAVASCRIPT

Validating Hexadecimal Color Codes

Validate both 3-digit and 6-digit hexadecimal color codes (e.g., #FFF, #00FFCC) with an efficient JavaScript regular expression for frontend development.

const isValidHexColor = (hexColor) => {
  const hexRegex = /^#([A-Fa-f0-9]{3}){1,2}$/;
  return hexRegex.test(hexColor);
};

console.log(isValidHexColor("#FFF"));     // true
console.log(isValidHexColor("#00FFCC")); // true
console.log(isValidHexColor("#abc"));     // true
console.log(isValidHexColor("#123456")); // true
console.log(isValidHexColor("FFF"));      // false (missing #)
console.log(isValidHexColor("#FG0"));     // false (invalid characters)
console.log(isValidHexColor("#1234"));    // false (invalid length)
How it works: The `isValidHexColor` function uses a regular expression to check if a string is a valid hexadecimal color code. It requires the string to start with `#` and be followed by either three or six hexadecimal characters (0-9, A-F, a-f). This is useful for validating user input in color pickers or parsing style attributes.

Need help integrating this into your project?

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

Hire DigitalCodeLabs