Skip to content
colors

isValidHex

The `isValidHex` function checks whether a given string is a valid 3-digit or 6-digit HEX color. It is a simple validation utility that ensures the input follows the HEX color format specification.

1 min read109 words

Function Signature

js

isValidHex(str: string): boolean

Parameters

  • str (string): The HEX color string to validate. It must start with a # and contain either 3 or 6 hexadecimal characters.

Return Value

Returns true if the string is a valid HEX color (#rgb or #rrggbb), otherwise returns false.

js

isValidHex("#fff");     // true
isValidHex("#ffffff"); // true
isValidHex("#123abc"); // true
isValidHex("123abc");  // false (missing #)
isValidHex("#abcd");   // false (invalid length)
isValidHex("#12g");    // false (invalid hex digit)

Examples

js

// Valid 3-digit HEX
console.log(isValidHex("#0af"));
// true

// Valid 6-digit HEX
console.log(isValidHex("#00aaff"));
// true

// Invalid HEX (no #)
console.log(isValidHex("00aaff"));
// false

Usage Notes

  • Validation is case-insensitive: both #ABC and #abc are valid.
  • This function does not expand shorthand HEX; use normalizeHex for that.
  • Commonly used as a pre-check before parsing or converting colors.

Previous

normalizeHex

Next

hexToRgb


Top-Werkzeuge

BoardlyLinksyChromoCodeHub

ReadyTools

KarriereKontaktWerkzeuge
Preise7 Tage gratis
AnleitungenDocsBlogUpdatesLaraVault

Sprache wählen

Thema wählen

© 2026 ReadyTools. Alle Rechte vorbehalten.