How to check if a string is a valid hexadecimal color representation?

For example:

AA33FF = valid hex color

Z34FF9 = invalid hex color (it has Z in it)

AA33FF11 = invalid hex color (has extra characters)

+105
javascript jquery colors
Nov 06 '11 at 13:50
source share
7 answers
 var isOk = /^#[0-9A-F]{6}$/i.test('#aabbcc') 

Develop:

^ start of the match
# hash [a-f0-9] any letter from af and 0-9
{6} previous group is displayed exactly 6 times
$ end of match
i ignore case

and more advanced:

  var isOk = /(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test('#ac3') // for #f00 (Thanks Smamatti) 
+244
Nov 06 '11 at 13:52
source share
β€” -
 function isHexaColor(sNum){ return (typeof sNum === "string") && sNum.length === 6 && ! isNaN( parseInt(sNum, 16) ); } isHexaColor("AA33FF") => true isHexaColor("Z34FF9") => false isHexaColor("AA33FF11") => false 

Change Please see @SalvadorDali's comment below, in some cases there are false positives. Rather, use a different solution.

+28
Nov 06 2018-11-11T00:
source share

This can be a difficult problem. After several attempts, I came up with a pretty clean solution. Let browswer do the work for you.

Step 1: Create a div with a border style of none. A div can be placed off-screen or it can be any div on your page that does not use borders.

Step 2. Set the border color to an empty string. The code might look something like this:

 e=document.getElementbyId('mydiv'); e.style.borderColor=""; 

Step 3. Set a border color for a color that you are not sure about.

 e.style.borderColor=testcol; 

Step 4: Check if the color has really changed. If testcol is invalid, there will be no change.

 col2=e.style.borderColor; if(col2.length==0) {alert("Bad Color!");} 

Step 5: Clean yourself by setting the color back to an empty string.

 e.style.borderColor=""; 

Div:

 <div id="mydiv" style="border-style:none; position:absolute; left:-9999px; top:-9999px;"></div> 

Now the JavaScript function:

 function GoodColor(color) { var color2=""; var result=true; var e=document.getElementById('mydiv'); e.style.borderColor=""; e.style.borderColor=color; color2=e.style.borderColor; if (color2.length==0){result=false;} e.style.borderColor=""; return result; } 

In this case, the function returns a true / false answer to the question, another option is to return the correct color value. Original color value, from borderColor value or empty string instead of invalid colors.

+8
Jan 25 '13 at 23:52
source share
 function validColor(color){ var $div = $("<div>"); $div.css("border", "1px solid "+color); return ($div.css("border-color")!="") } 

https://gist.github.com/dustinpoissant/22ce25c9e536bb2c5a2a363601ba261c

Note: this requires jQuery

This works for ALL color types, not just hexadecimal values. It also does not add unnecessary elements to the DOM tree.

+2
Nov 20 '16 at 17:08
source share

If you need a function to tell you if a color is real, you can also give it something useful β€” the computed values ​​of that color β€” and return null if it is not a valid color. Here I click on a compatible (Chrome54 and MSIE11) function to get the RGBA color values ​​in any of the formats - be it green or #FFF, or # 89abcd, or rgb (0,0,128) 'or' rgba (0, 128, 255, 0.5) '.

 /* getRGBA: Get the RGBA values of a color. If input is not a color, returns NULL, else returns an array of 4 values: red (0-255), green (0-255), blue (0-255), alpha (0-1) */ function getRGBA(value) { // get/create a 0 pixel element at the end of the document, to use to test properties against the client browser var e = document.getElementById('test_style_element'); if (e == null) { e = document.createElement('span'); e.id = 'test_style_element'; e.style.width = 0; e.style.height = 0; e.style.borderWidth = 0; document.body.appendChild(e); } // use the browser to get the computed value of the input e.style.borderColor = ''; e.style.borderColor = value; if (e.style.borderColor == '') return null; var computedStyle = window.getComputedStyle(e); var c if (typeof computedStyle.borderBottomColor != 'undefined') { // as always, MSIE has to make life difficult c = window.getComputedStyle(e).borderBottomColor; } else { c = window.getComputedStyle(e).borderColor; } var numbersAndCommas = c.replace(new RegExp('[^0-9.,]+','g'),''); var values = numbersAndCommas.split(','); for (var i = 0; i < values.length; i++) values[i] = Number(values[i]); if (values.length == 3) values.push(1); return values; } 
+1
Dec 09 '16 at 16:44
source share

If you are trying to use it in HTML, try using this template directly:

  pattern="^#+([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$" 

like

 <input id="hex" type="text" pattern="^#+([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$" /> 

This will confirm according to the requested format.

+1
Apr 17 '18 at 4:15
source share

Add a length check to make sure you don't get a false positive

 function isValidHex(testNum){ let validHex = false; let numLength = testNum.length; let parsedNum = parseInt(testNum, 16); if(!isNan(parsedNum) && parsedNum.length===numLength){ validHex = true; } return validHex; 

}

0
Apr 08 '19 at 22:24
source share



All Articles