-2

I want to validate a string value from textbox.

Validation requirements are:

  1. Exactly 2 characters
  2. Hex characters only

How can I do this?

Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
mixo_17
  • 127
  • 1
  • 1
  • 8

4 Answers4

3

Use a Regex validator control with the expression: ^[0-9A-F]{2}$

Naftuli Kay
  • 87,710
  • 93
  • 269
  • 411
Sam
  • 9,933
  • 12
  • 68
  • 104
  • 2
    by the way, if you want to allow lowercase, you'll need to account for that as well: ^[0-9A-Fa-f]{2}$ – Sam Dec 20 '11 at 22:09
1
             String^ temp = "012345679abcdefABCDEF";
             if (temp->IndexOf(e->KeyChar) == -1)
             {
                 e->Handled = true;
             }

use this for hex character control

1

You could use a regular expression, something like:

^([0-9A-F]{2})$
Glory Raj
  • 17,397
  • 27
  • 100
  • 203
JeffCren
  • 396
  • 1
  • 5
  • 15
0

//Use this method and before calling it ..pass or parse out the string.Substring(0,2)

public string ConvertToHex(string asciiString)
{ 
    var newasciiString = Substring(asciiString,0,2);
    string hex = "";
    foreach (char c in newasciiString)
    {
        int tmp = c;
        hex += String.Format("{0:x2}", (uint)System.Convert.ToUInt32(tmp.ToString()));
    }
    return hex;
} 
MethodMan
  • 18,625
  • 6
  • 34
  • 52