Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to check valid hex? 2

Status
Not open for further replies.

serpento

Programmer
Jun 16, 2002
92
GB
What's a quick way to check that a six character string is a valid hex value (i.e. contains only numbers and letters A-F?)? I expect it would invlove regular expressions but haven't got the hang of them yet, so would apprieciate some help.

-Ed ;-)

________________________________
Destiny is not a matter of chance; it is a matter of choice.
 
javascript likes to see "0X" infront of a hex value.

therefore...

<script>
function isHex(){
inHex = document.myForm.myVal.value
if (isNaN(parseInt(&quot;0X&quot; + inHex))) {
alert(inHex + &quot; is not valid &quot;)
}
else{
alert(inHex + &quot; is valid &quot;)
}
}
</script>

<form name=&quot;myForm&quot;>
<input name=&quot;myVal&quot;>
<input type=button onClick=&quot;isHex()&quot; value=&quot;Check&quot;>

please note that this is just a starting point. ParseInt will return a number if the hex starts with a valid number. For instance &quot;AA45XX&quot; will return valid here, but &quot;XX&quot; will not...

Programming today is a race between software engineers striving to build better and bigger idiot-proof programs, and the Universe trying to produce bigger and better idiots. So far, the Universe is winning. - Rick Cook
 
Thanks loads for your help! Here's the code I'm using in the end:
Code:
  function isHex(string)
  {
    if (string.length!=6) return false;
    for (i=0; i<6; i++)
    {
      if (isNaN(parseInt(string.charAt(i), 16)))
        {return false;}
    }
    return true;
  }

-Ed ;-)

________________________________
Destiny is not a matter of chance; it is a matter of choice.
 
serpento,

good idea using parseInt with radix 16...i've condensed the function for you - it should work the same:

function isHex(s) {
return (s.length &&
!(s.length != 6 || isNaN(parseInt(s,16))))
}

=========================================================
-jeff
try { succeed(); } catch(E) { tryAgain(); }
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top