Stopping some keys in the editing window

So, I already have the code. But when it starts, it does not allow the backspace key to be used, I need this to enable the backspace key and remove the space, since 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 to: D

+5
source share
3 answers

Pay attention to the comment already contained 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;
+6
source

It is better to put the permission keys in the set as a constant (speed, optimization):

Updated # 2 Allow only one decimal char and handle DecimalSeparator correctly.

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 more accurate results, take a look at the TNumericEdit components included with DevExpress, JVCL, EhLib, RxLib, and many other libraries.

+3

, , .

You can use the OnExit event of the control or the Ok / Save object of your form to check the correct format as follows:

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 specific decimal separator for the locale.

If you want to allow '.', you can pass the entry TFormatSettingsas the third parameter to TryStrToFloat.

+1
source

All Articles