JavaScript Find Hexadecimal Numbers

From Regex Regular Expression Encyclopedia

Jump to: navigation, search

This recipe will limit the input to numbers and letters that are valid for hexadecimal representations.

[edit] code

<html>
<head>
<title></title>
</head>
<body>
<form name="form1">
    <input type="textbox" name="txtInput" />
    <script type="text/javascript">
    function validate() {
        if (! document.form1.txtInput.value.match(/^[0-9a-f]+$/i)) {
            alert("Please enter valid value!")
        } else {
            alert("Success!")
        }
    }
    </script>
    <input type="button" name="btnSubmit" onclick="validate()" value="Go" />
</form>
</body>
</html>

[edit] How It Works

This recipe uses a simple character class to limit the input to digits and the letters a through f:

Regular Expression Description
^ the beginning of the line, followed by . . .
[0-9a-f] a character class that matches the digits zero through nine and the letters
\s a through f . . .
+ found one or more times . . .
$ the end of the line.

Alternatively, you can replace 0-9 in the character class with \d.

Personal tools