Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Javascript Regex, how do I validate that a string is a valid hexadecimal colour?

Given a string like #fff443 or #999999

How do I verify that the string has:

  • 7 characters, with the first one being a hash
  • no symbols in the string besides the hash in the beginning
like image 678
TIMEX Avatar asked Jan 15 '12 09:01

TIMEX


People also ask

How do you check if a string is a valid hex color?

The length of the hexadecimal color code should be either 6 or 3, excluding '#' symbol. For example: #abc, #ABC, #000, #FFF, #000000, #FF0000, #00FF00, #0000FF, #FFFFFF are all valid Hexadecimal color codes.

Is hex valid?

Yes, in hexadecimal, things like A, B, C, D, E, and F are considered numbers, not letters. That means that 200 is a perfectly valid hexadecimal number just as much as 2FA is also a valid hex number.

What is the regular expression for a valid HTML hex color value?

regex = "^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$"; Where: ^ represents the starting of the string. # represents the hexadecimal color code must start with a '#' symbol.


1 Answers

It seems that you are matching against a css color:

function isValidColor(str) {
    return str.match(/^#[a-f0-9]{6}$/i) !== null;
}

To elaborate:

^ match beginning
# a hash
[a-f0-9] any letter from a-f and 0-9
{6} the previous group appears exactly 6 times
$ match end
i ignore case

like image 57
qiao Avatar answered Oct 03 '22 10:10

qiao