2

I am writing some javascript to validate user input in a text area. Here are the requirements for input format:

  1. Input must be in the format of two hex values separated by a space (i.e. A7 B3 9D).
  2. Input must be valid hex values.

I have requirement #2 sorted out with a regExpression valueOne.match("[0-9A-Fa-f]{1}") (or at least I hope that is the recommended way to do it). So I am just looking for some input on how to go about handling requirement number one in a simple and efficient way.

Thanks!

4

1 回答 1

5

This regex will do it:

/^[0-9A-F]{2}(\s[0-9A-F]{2})*$/i

That is:

^                // beginning of string
[0-9A-F]{2}      // two characters of 0-9 or A-F
(\s[0-9A-F]{2})* // zero or more instances of a space followed by
                 // two characters of 0-9 or A-F
$                // end of string

Where the i flag at the end makes it case insensitive.

To use it:

 var valueOne = // set to your textarea's value here
 if (/^[0-9A-F]{2}(\s[0-9A-F]{2})*$/i.test(valueOne)) {
     // is OK, do something
 } else {
     // is not OK, do something
 }
于 2012-09-11T03:09:14.517 回答