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

后端 未结 7 516
迷失自我
迷失自我 2020-11-28 03:47

For example:

AA33FF = valid hex color

Z34FF9 = invalid hex color (has Z in it)

AA33FF11 = invalid hex color (h

7条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-28 04:06

    Add a length check to make sure that 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;
    

    }

提交回复
热议问题