-3
else if (vReadData.Length==14 && vReadData Is Numeric)
{
    if (txtIPLoad_MHEBarcode1.Text == "")
{
    txtIPLoad_MISBarcode1.Text = vReadData;
    txtIPLoad_MHEBarcode1.Focus();
}
else
{
    txtIPLoad_MISBarcode2.Text = vReadData;
    txtIPLoad_MHEBarcode2.Focus();
}
    mMessage("Scan", "Please scan the MHE Barcode!");
    return;
}

This is my code for validating a Textbox. I check the condition that the length should be 14 chars. I must also check that the input which comes in variable vReadData must be numeric (only numbers). Please help me solve this.

I have tried using

 else if (Int64.TryParse(vReadData, out num))

but this is not helping me.

Maciej Kowalski
  • 25,605
  • 12
  • 54
  • 63
Santhosh Raja
  • 39
  • 1
  • 9

1 Answers1

1

Are you looking for a regular expression?

 else if (Regex.IsMatch(vReadData, @"^[0-9]{14}$")) {
   // vReadData is a string of exactly 14 digits [0..9] 
 }

Explanation: we have to match two conditions

  1. The string should be exactly 14 characters long
  2. It should be a valid (non-negative) number (I doubt if any negative bar code exits)

After combining both conditions into one we can say that we're looking for a string which consist of 14 digits [0-9] (please notice, that we want [0-9] not \d, since \d in .Net means any digit, including, say Persian ones)

Tests:

string vReadData = @"B2MX15235687CC";
// vReadData = @"12345678901234";

if (Regex.IsMatch(vReadData, @"^[0-9]{14}$"))
  Console.Write("Valid");
else
  Console.Write("InValid"); 

Outcome:

InValid

If you uncomment the line you'll get

Valid 
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215