Sunday, June 2, 2024
 Popular · Latest · Hot · Upcoming
184
rated 0 times [  190] [ 6]  / answers: 1 / hits: 130422  / 13 Years ago, sun, november 6, 2011, 12:00:00

For example:



AA33FF = valid hex color



Z34FF9 = invalid hex color (has Z in it)



AA33FF11 = invalid hex color (has extra characters)


More From » jquery

 Answers
0
/^#[0-9A-F]{6}$/i.test('#AABBCC')

To elaborate:


^ -> match beginning

# -> a hash

[0-9A-F] -> any integer from 0 to 9 and any letter from A to F

{6} -> the previous group appears exactly 6 times

$ -> match end

i -> ignore case


If you need support for 3-character HEX codes, use the following:


/^#([0-9A-F]{3}){1,2}$/i.test('#ABC')

The only difference here is that


 [0-9A-F]{6}

is replaced with


([0-9A-F]{3}){1,2}

This means that instead of matching exactly 6 characters, it will match exactly 3 characters, but only 1 or 2 times. Allowing ABC and AABBCC, but not ABCD


Combined solution :


var reg=/^#([0-9a-f]{3}){1,2}$/i;
console.log(reg.test('#ABC')); //true
console.log(reg.test('#AABBCC')); //true

[#89278] Friday, November 4, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
sageallenv

Total Points: 458
Total Questions: 102
Total Answers: 104

Location: Venezuela
Member since Thu, Jul 15, 2021
3 Years ago
;