Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to accept letters only in TEdit? 2

Status
Not open for further replies.

doctorjellybean

Programmer
May 5, 2003
145
TEdit has a NumbersOnly property, but I only want letters as input allowed. I've tried all sorts of code, Googled, but can't find a solution. I have 3 edit boxes, each containing only a single character (MaxLength = 1). When a user enters a number, then nothing should happen. Only when a letter is entered, then it is displayed.

Thanks in advance.
 
wheres the NumbersOnly property??

numbers only
Code:
procedure TForm1.Edit1KeyPress(Sender: TObject; var Key: Char);
begin
  // #8 is Backspace
  if not (Key in [#8, '0'..'9']) then
  begin
    ShowMessage('Invalid key');
    // Discard the key
    Key := #0;
  end;
end;

letters only
Code:
procedure TForm1.Edit1KeyPress(Sender: TObject; var Key: Char);
begin
  if (Key in ['0'..'9']) then
  begin
    ShowMessage('Invalid key');
    // Discard the key
    Key := #0;
  end;
end;

Aaron
 
While the answer above was good, it might be good to be more explicit with what you are looking for. If you really want just "letters" and not all alphanumerics besides numbers, it would be good to test for those exclusively:

Code:
procedure TForm1.Edit1KeyPress(Sender: TObject; var Key: Char);
  { validate keypress, only return value if alphabetic }
begin
  if Key in ['A'..'Z', 'a'..'z'] then
  else
    Key := #0;
end;

If backspace/tab gets stuffed, aaronjme's first example shows how to handle it (the backspace, anyhow). You can do that, as well, to explicitly add any other characters you deem necessary to your project at hand.

Measurement is not management.
 
Thanks Glenn and aaronjme.

aaronjme, Delphi 2009 has a NumbersOnly property for TEdit.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top