JAVASCRIPT

Validate Hexadecimal Color Codes with Regular Expressions

Quickly validate CSS hexadecimal color codes (e.g., #FFF, #FFFFFF) using a simple yet effective regular expression in JavaScript for forms or styling tools.

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

console.log(isValidHexColor("#FFF"));     // true
console.log(isValidHexColor("#FFFFFF"));  // true
console.log(isValidHexColor("#f0c"));     // true
console.log(isValidHexColor("#F0C3D4"));  // true
console.log(isValidHexColor("ABC"));      // false (missing #)
console.log(isValidHexColor("#1234"));    // false (invalid length)
console.log(isValidHexColor("#GGGGGG"));  // false (invalid characters)
How it works: The `isValidHexColor` function uses a regular expression to determine if a string represents a valid 3-digit or 6-digit hexadecimal color code, optionally prefixed with a '#'. The regex pattern ensures the string starts with '#' and is followed by either three or six valid hexadecimal characters (0-9, A-F, a-f). This is commonly used in design tools or input validation for color pickers.

Need help integrating this into your project?

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

Hire DigitalCodeLabs