JAVASCRIPT

Validate Hexadecimal Color Code Format

Use a JavaScript regex to validate hexadecimal color codes, supporting 3-digit and 6-digit formats, with or without a leading hash symbol, for CSS or UI inputs.

function isValidHexColor(hex) {
  const hexColorRegex = /^#?([0-9a-fA-F]{3}){1,2}$/;
  return hexColorRegex.test(hex);
}

// Examples
console.log(isValidHexColor('#FF00FF')); // true
console.log(isValidHexColor('FFF'));      // true
console.log(isValidHexColor('#abc'));     // true
console.log(isValidHexColor('invalid'));  // false
console.log(isValidHexColor('#GG00FF')); // false
How it works: The `isValidHexColor` function checks if a string is a valid hexadecimal color code using a regular expression. It accepts both 3-digit and 6-digit hex codes, optionally preceded by a hash (`#`) symbol. This is valuable for validating user input for color pickers or CSS property values.

Need help integrating this into your project?

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

Hire DigitalCodeLabs