I have a application that needs to accept float or currency values in edit control. My q开发者_开发问答uestion 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.
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;
Just get the JVCL and use the TJvValidateEdit component.
精彩评论