How is right to format and validate edit control to accept only float or currency values

五迷三道 提交于 2020-01-05 04:30:18

问题


I have a application that needs to accept float or currency values in edit control. My question is what I must to do to format and validate edit controls input so it accepts only numbers, comma or dot (comma or dot depends on system locale). And the formatting is ##.## (45.21). I want to do one method that can control all edit controls wehre float formatting and validating is used.

Right now I have code in OnChange event that uses TryStrToFloat method, but sometimes I get "'' is not floating point number" errors.

Maybe you guys have done it more than me and have some great examples how to do it right.


回答1:


If you want to continue using the same validation approach, just enhance your algorithm to consider the edge cases (and how you want to manage that).

For example, you can consider accepting an empty string as a valid input and just don't throw an exception, or not. You must also consider how do you want to perform the user interaction in case of malformed input. For example if a user enters a invalid number, you want to stop the user to input values at that same millisecond... or you can take a more natural approach (for example, validating until the user thinks everything is correct).

You can also manage validation just by notifying the user in a non-stoper way while the input is being done, just making a visible effect over the offending fields, and in a stopper way (for example with a message box) if the user tries to save the data.

A simple validation function may look like this:

function IsEditValidFloat(Sender: TEdit; const AcceptBlank: Boolean = True): Boolean;
var
  sValue: string;
  Temp: Extended;
begin
  sValue := Trim(Sender.Text);
  if (sValue.Text = '') then
    Result := AcceptBlank
  else
    Result := TryStrToFloat(sValue, Temp);
end;

//you might call this on the OnChangeEvent:
procedure TForm1.Edit1Change(Sender: TObject);
begin
  if IsEditValidFloat(Sender as TEdit) then
    ChangeDisplayState(Sender, dsValid)
  else
    ChangeDisplayState(Sender, dsError);
end;



回答2:


Just get the JVCL and use the TJvValidateEdit component.



来源:https://stackoverflow.com/questions/5033078/how-is-right-to-format-and-validate-edit-control-to-accept-only-float-or-currenc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!