jquery 如何检查字符串是否是有效的十六进制颜色表示?

brtdzjyr  于 2022-12-22  发布在  jQuery
关注(0)|答案(9)|浏览(196)

例如:
AA33FF =有效的十六进制颜色
Z34FF9 =无效的十六进制颜色(其中包含Z)
AA33FF11 =无效的十六进制颜色(具有额外字符)

z9ju0rcb

z9ju0rcb1#

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

详细说明:
^ ->匹配开始
# ->哈希
[0-9A-F] -> 0到9之间的任何整数和A到F之间的任何字母
{6} ->前一组正好出现6次
$ ->匹配结束
i ->忽略大小写
如果需要支持3个字符的十六进制代码,请使用以下命令:

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

唯一的区别是

[0-9A-F]{6}

被替换为

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

这意味着它将只匹配3个字符,而不是只匹配6个字符,但只匹配1或2次。允许ABCAABBCC,但不允许ABCD

    • 合并解决方案:**
var reg=/^#([0-9a-f]{3}){1,2}$/i;
console.log(reg.test('#ABC')); //true
console.log(reg.test('#AABBCC')); //true
qxgroojn

qxgroojn2#

// regular function
function isHexColor (hex) {
  return typeof hex === 'string'
      && hex.length === 6
      && !isNaN(Number('0x' + hex))
}

// or as arrow function (ES6+)
isHexColor = hex => typeof hex === 'string' && hex.length === 6 && !isNaN(Number('0x' + hex))

console.log(isHexColor('AABBCC'))   // true
console.log(isHexColor('AABBCC11')) // false
console.log(isHexColor('XXBBCC'))   // false
console.log(isHexColor('AAXXCC'))   // false

这个答案过去常常抛出假阳性,因为它使用的是parseInt(hex, 16)而不是Number('0x' + hex)
parseInt()将从字符串的开头进行分析,直到到达不包含在基数(16)中的字符。这意味着它可以分析'AAXXCC'之类的字符串,因为它以'AA'开头。
另一方面,Number()只在整个字符串与基数匹配时才进行解析,现在,Number()不带radix参数,但幸运的是,您可以在前面加上数字常量,以获得其他半径的数字。
下面是一个表格,用于说明:

╭─────────────┬────────────┬────────┬───────────────────╮
│ Radix       │ Characters │ Prefix │ Will output 27    │
╞═════════════╪════════════╪════════╪═══════════════════╡
│ Binary      │ 0-1        │ 0b     │ Number('0b11011') │
│ Octal       │ 0-7        │ 0o     │ Number('0o33')    │
│ Decimal     │ 0-9        │ -      │ -                 │
│ Hexadecimal │ 0-9A-F     │ 0x     │ Number('0x1b')    │
╰─────────────┴────────────┴────────┴───────────────────╯
wb1gzix0

wb1gzix03#

这可能是一个复杂的问题。经过几次尝试,我想出了一个相当干净的解决方案。让浏览器为你做这项工作。
第一步:创建一个边框样式设置为none的div。这个div可以放在屏幕外,也可以是页面上不使用边框的任何div。
步骤2:将边框颜色设置为空字符串。代码可能如下所示:

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

第三步:将边框颜色设置为您不确定的颜色。

e.style.borderColor=testcol;

第四步:检查颜色是否真的改变了。如果testcol无效,则不会发生任何改变。

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

第5步:通过将颜色设置回空字符串来进行清理。

e.style.borderColor="";

事业部:

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

现在JavaScript函数:

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;
}

在这种情况下,函数返回问题的真/假答案,另一种选择是让它返回一个有效的颜色值。您的原始颜色值、来自borderColor的值或空字符串代替无效颜色。

xdnvmnnf

xdnvmnnf4#

如果您尝试在HTML中使用它请直接使用此模式:

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

喜欢

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

它将给予验证以匹配请求的格式。

5m1hhzi4

5m1hhzi45#

function validColor(color){
  var $div = $("<div>");
  $div.css("border", "1px solid "+color);
  return ($div.css("border-color")!="")
}

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

  • 注意:这需要jQuery*

这适用于所有颜色类型,而不仅仅是十六进制值。它也向DOM树追加不必要的元素。

zour9fqk

zour9fqk6#

如果您需要一个函数来告诉您某个颜色是否有效,那么您最好让它给予一些有用的东西--该颜色的计算值--并在它不是有效颜色时返回null。(Chrome 54 & MSIE 11)函数获取任何格式的“颜色”的RGBA值--可以是“green”、"#FFF“、" #89abcd”或“rgb(0,0,128)“或”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;
}
41zrol4v

41zrol4v7#

添加长度检查以确保不会得到误报

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;

}

eanckbw9

eanckbw98#

我决定换个Angular 看问题,我的原则是:1)十六进制字符的任意长序列,2)在序列的前面使用“0x”或“#”,或者3)只是一个十六进制数或字符串。我回想起binhex是一个大程序的时候。Binhex会创建非常大的文件,可以传输到任何地方,然后再转换回任何文件。这些文件有80个字符,后面跟着一个return。所以在这个函数中,我先查找return,然后把它们取出来。修改了这个函数,这样它就可以同时查找“\n”和“\r”。下面是代码:

////////////////////////////////////////////////////////////////////////////////
//  isHex(). Is this a hex string/value?
//  Arguments   :   0   =   Item to test
//                  1   =   V(alue) or S(tring). Default is STRING.
////////////////////////////////////////////////////////////////////////////////
function isHex()
{
    var p = 0;
    var re1 = /(\n|\r)+/g;
    var re2 = /[\Wg-zG-Z]/;
    var re3 = /v/i;
//
//  Make sure the string is really a string.
//
    var s = arguments[0];
    if( typeof s != "string" ){ s = s.toString(); }
//
//  Check if this is a hex VALUE
//  and NOT a hex STRING.
//
    var opt = arguments[1];
    if( re3.test(opt) && (s.length % 2 > 0) ){ return "false"; }
//
//  Remove any returns. BinHex files can be megabytes in length with 80
//  column information. So we have to remove all returns first.
//
    s.replace( re1, "" );
//
//  IF they send us something with the universal "0x" or the HTML "#" on the
//  front of it - we have to FIRST move where we look at the string.
//
    if( s.substr(0,1) == "#" ){ p = 1; }
        else if( s.substr(0,2).toLowerCase() == "0x" ){ p = 2; }

   if( re2.test(s.substr(p,s.length)) ){ return "false"; }

   return "true";
}

alert("HELLO There!");
alert(isHex("abcdef"));
alert(isHex("0x83464"));
alert(isHex("#273847"));
alert(isHex("This is a test"));
alert(isHex(0x5346));

我特意将返回值保留为字符串,但您所要做的就是删除双引号,然后函数将只返回TRUE或FALSE。

km0tfn4u

km0tfn4u9#

如果希望支持ARGB,则支持的十六进制数字为3、4、6、8。

const isColor = (strColor) => {
  return /^#(([0-9A-Fa-f]{2}){3,4}|[0-9A-Fa-f]{3,4})$/.test(strColor)
}

请注意,{2}应该在{3,4}之前,以确保7位十六进制可以正确地检查为false

相关问题