2008. március 24., hétfő

Restrict TEdit input to floating point numbers and a defined number of decimal places


Problem/Question/Abstract:

I would like a TEdit box on my form that only accepts keys to enter a floating point number that has N number of decimal places. What is the best way to do this?

Answer:

Derive a new component from TEdit and override its KeyPress method. That is fed characters before the control has inserted them into the text. You can examine the character, reject it outright if it would not be valid for a floating point number. If it would be valid you have to examine the content of the edit, the values of SelStart and SelCount and figure out how the content would look like if you let the key pass throuogh. Test that new string against what you can accept, if it does not match you reject the key. The following OnKeyPress handler for a normal tedit control shows the logic. It should be integrated into a new component which also would have a property to set the number of allowable decimal digits.

procedure TForm1.Edit1KeyPress(Sender: TObject; var Key: Char);
const
  MAXNUMBEROFDIGITS = 2;
var
  S: string;
  val: Double;
  n: Integer;
begin
  if key <> #8 then {Always let backspace through}
    if key in ['0'..'9', '-', DecimalSeparator] then
    begin
      {key is a candidate}
      with Sender as TEdit do
      begin
        S := Text;
        if SelLength > 0 then {key will replace selection}
          Delete(S, SelStart + 1, SelLength);
        Insert(key, S, SelStart + 1);
        {S now has string as it would look after key is processed. Check if it is a valid floating point number.}
        try
          val := StrToFloat(S);
          {OK, it computes. Find the decimal point and count the digits after it.}
          n := Pos(decimalSeparator, S);
          if n > 0 then
            if (Length(S) - n) > MAXNUMBEROFDIGITS then
              {too many digits, reject key}
              key := #0;
        except
          {nope, reject key}
          key := #0;
        end;
      end;
    end
    else {key not acceptible}
      key := #0;
end;

Nincsenek megjegyzések:

Megjegyzés küldése