Prevent character typing, if the monetary value is incorrect in delphi

1

My goal, using Delphi 10.1, is to compare the typed text in an Edit, at the time of typing a new character, if the text format after typing the key (which can be typed at the end, beginning or middle of the text existing ") would still" be "a valid monetary value, allowing only 2 decimal places.

And if the "future value" is not valid, do not enter the key.

I know JvValidateEdit or JvEdit does almost this, if you prevent paste, but they allow you to type as many decimal places as you want, and round to the programmed value (Ex: 2 ) upon exiting. It would be nice if I could limit both invalid characters and the homes at the time of typing.


At first it seemed easy, I compared it to the OnKeyPress event of a TEdit , using a formula of mine to check if it is a valid monetary value with up to 2 decimal places:

//stValor := Edit1.Text + Key;
if not IsValidMoeda_1(stValor) then
key = #0;


current formula:

function isValidMoeda_1(Valor: string):Boolean;//Teste
begin
  Result:=False;

  if TRegEx.IsMatch(Valor, '^(?:[0-9]{0,14}|0)(?:,\d{0,2})?$') then
    begin
      Result:=True;
    end;

end;


It even seemed to work, but it does not work if the key is typed at the beginning, or anywhere in the middle of the text. Then I thought it was impossible, but then, I saw software that does this, giving freedom to whoever it is typing, and just barring the key if the future sequence is invalid.

Of course, there is the option as banks do: send the new key always typed to the end of the string, or just allow numbers in the edit, and then divide the value by 100, but it would be kind of intrusive for what I want.

Is there any way to get the new text to compare, but still in time to invalidate the key?

    
asked by anonymous 15.07.2018 / 03:19

1 answer

3

To work in any position, you need to check the cursor position and selection size:

function isValidMoeda(Valor: string): Boolean;
begin
  Result := TRegEx.IsMatch(Valor, '^(?:[0-9]{0,14}|0)(?:,\d{0,2})?$');
end;

procedure TForm1.Edit1KeyPress(Sender: TObject; var Key: Char);
var
  p, l: integer;
  s: string;
begin
  p := Edit1.SelStart + 1;
  l := Edit1.SelLength;
  s := Edit1.Text;
  delete(s, p, l);
  insert(Key, s, p);
  if not isValidMoeda(s) then
    Key := #0;
end;
    
15.07.2018 / 18:08