Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stopping Certain Keys in an Edit Box

Tags:

browser

delphi

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

like image 737
Matt Biggs Avatar asked Jul 31 '12 08:07

Matt Biggs


People also ask

How do I restrict a key in Javascript?

You should try to block only the specific key you don't want. So keypress event get the pressed key before this character enter in your input. You also can use event. preventDefault() to block this specific key you don't want.

How do you check if Enter key is pressed in Javascript?

And the following JavaScript code to detect whether the Enter key is pressed: const input = document. querySelector("input"); input. addEventListener("keyup", (event) => { if (event.


3 Answers

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;
like image 138
Sertac Akyuz Avatar answered Oct 12 '22 17:10

Sertac Akyuz


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.

like image 39
Marcodor Avatar answered Oct 12 '22 16:10

Marcodor


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.

like image 34
Jens Mühlenhoff Avatar answered Oct 12 '22 17:10

Jens Mühlenhoff