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
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.
And the following JavaScript code to detect whether the Enter key is pressed: const input = document. querySelector("input"); input. addEventListener("keyup", (event) => { if (event.
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;
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With