Matt Biggs
Matt Biggs

Reputation: 177

Stopping Certain Keys in an Edit Box

So i have code already. But when it runs it doesn't allow the backspace key, I need it to allow the backspace key and remove the space bar as I don't want spaces.

procedure TForm1.AEditAKeyPress(Sender: TObject; var Key: Char);
var s:string;
begin
s := ('1 2 3 4 5 6 7 8 9 0 .'); //Add chars you want to allow
if pos(key,s) =0 then begin Key:=#0;
showmessage('Invalid Char');
end;

Need help thanks :D

Upvotes: 7

Views: 6867

Answers (3)

Marcodor
Marcodor

Reputation: 5741

It's better to put your allow keys in a set as a constant (speed, optimization):

Updated #2 Allow only one decimal char and handling properly DecimalSeparator.

procedure TForm1.Edit1KeyPress(Sender: TObject; var Key: Char);
const
  Backspace = #8;
  AllowKeys: set of Char = ['0'..'9', Backspace];
begin
  if Key = '.' then Key := DecimalSeparator;
  if not ((Key in AllowKeys) or
    (Key = DecimalSeparator) and (Pos(Key, Edit1.Text) = 0)) then
  begin
    ShowMessage('Invalid key: ' + Key);
    Key := #0;
  end;
end;

For better results take a look at TNumericEdit components included in DevExpress, JVCL, EhLib, RxLib and many other libraries.

Upvotes: 5

Jens Mühlenhoff
Jens Mühlenhoff

Reputation: 14873

Using psychic powers, I predict that you're trying to validate a floating point value.

You can use the OnExit event of the control or the Ok/Save facility of your form to check the correct format like this:

procedure TForm1.Edit1Exit(Sender: TObject);
var
  Value: Double;
begin
  if not TryStrToFloat(Edit1.Text, Value) then begin
    // Show a message, make Edit1.Text red, disable functionality, etc.
  end;
end;

This code assumes that you want to use a locale specific decimal separator.

If you only want to allow a '.' you can pass a TFormatSettings record as the third parameter to TryStrToFloat.

Upvotes: 1

Sertac Akyuz
Sertac Akyuz

Reputation: 54792

Note the comment that's already in your code:

procedure TForm1.AEditKeyPress(Sender: TObject; var Key: Char);
var s:string;
begin
  s := ('1234567890.'#8); //Add chars you want to allow
  if pos(key,s) =0 then begin
    Key:=#0;
    showmessage('Invalid Char');
  end;
end;

Upvotes: 9

Related Questions