c++c++builderc++builder-xe8

TEdit Input Validation on C++ Builder XE8


I am very new to C++ Builder XE8.

I want the minimum and maximum length of numbers that must be typed is as much as six numbers, also I need to make sure that only number is entered (0 is exception), and not an alphabetic character, backspace, punctuation, etc.

I would also like to produce an error box if anything other than a number is entered.

I've tried a few combinations of codes, three of which can be seen below, but none of those codes works.

Any help would sure be appreciated!

(1).

void __fastcall TForm1::Edit1KeyPress(TObject *Sender, System::WideChar &Key)
{
  Edit1->MaxLength = 6;

  if (!((int)Key == 1-9)) {
  ShowMessage("Please enter numerals only");
  Key = 0;
  }
}

(2).

void __fastcall TForm1::Edit1KeyPress(TObject *Sender, System::WideChar &Key)
{
  Edit1->MaxLength = 6;

  if (Key <1 && Key >9) {
  ShowMessage("Please enter numerals only");
  Key = 0;
  }
}

(3).

void __fastcall TForm1::Edit1KeyPress(TObject *Sender, System::WideChar &Key)
{
  Edit1->MaxLength = 6;

  if( Key == VK_BACK )
   return;

  if( (Key >= 1) && (Key <= 9) )
   {
  if(Edit1->Text.Pos(1-9) != 1 )
   ShowMessage("Please enter numerals only");
   Key = 1;
  return;
  }
}

Solution

  • TEdit has a NumbersOnly property:

    Allows only numbers to be typed into the text edit.

    Set it to true and let the OS handle the validation for you. But, if you want to validate it manually, use this:

    void __fastcall TForm1::Edit1KeyPress(TObject *Sender, System::WideChar &Key)
    {
        // set this at design-time, or at least
        // in the Form's constructor. It does not
        // belong here...
        //Edit1->MaxLength = 6;
    
        if( Key == VK_BACK )
            return;
    
        if( (Key < L'0') || (Key > L'9') )
        {
            ShowMessage("Please enter numerals only");
            Key = 0;
        }
    }