TEdit Input Validation on C++ Builder XE8

白昼怎懂夜的黑 提交于 2019-12-24 03:04:31

问题


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;
  }
}

回答1:


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;
    }
}



回答2:


Check out TMaskEdit: http://docs.embarcadero.com/products/rad_studio/delphiAndcpp2009/HelpUpdate2/EN/html/devwin32/idh_useop_textcontrols_xml.html

TMaskEdit is a special edit control that validates the text entered against a mask that encodes the valid forms the text can take. The mask can also format the text that is displayed to the user.

EDIT: To set a minimum length

void __fastcall TForm1::MaskEdit1Exit(TObject *Sender)
{
   if (MaskEdit1->Text.length() < 6)
   {
     //your error message, or throw an exception.
   }
}


来源:https://stackoverflow.com/questions/31800094/tedit-input-validation-on-c-builder-xe8

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!