2

我对 C++ Builder XE8 很陌生。

我希望必须输入的数字的最小和最大长度为六个数字,我还需要确保只输入数字(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;
  }
}
4

2 回答 2

2

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;
    }
}
于 2015-08-04T03:49:13.570 回答
1

查看TMaskEdithttp ://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.
   }
}
于 2015-08-04T03:48:40.767 回答