c++ Builder XE8上的TEdit输入验证

TEdit Input Validation on C++ Builder XE8

本文关键字:输入 验证 TEdit 上的 Builder XE8 c++      更新时间:2023-10-16

我是c++ Builder XE8的新手。

我希望必须键入的数字的最小和最大长度最多为6个数字,我还需要确保只输入数字(0是例外),而不是字母字符,退格,标点符号等。

我还想产生一个错误框,如果输入除数字以外的任何东西。

我尝试了一些代码组合,其中三种可以在下面看到,但这些代码都不起作用。

任何帮助都将非常感激!

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

TEdit具有NumbersOnly属性:

只允许在文本编辑中输入数字。

将其设置为true,让操作系统为您处理验证。但是,如果您想手动验证它,请使用以下命令:

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

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

TMaskEdit是一个特殊的编辑控件,它根据对文本可以采用的有效形式进行编码的掩码来验证输入的文本。掩码还可以格式化显示给用户的文本。

编辑:设置最小长度

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