如何正确格式化和验证编辑控件以仅接受浮点或货币值
我有一个应用程序需要在编辑控件中接受浮动或货币值。我的问题是我必须做什么来格式化和验证编辑控件输入,以便它只接受数字、逗号或点(逗号或点取决于系统区域设置)。格式为##.## (45.21)。我想做一种可以控制使用浮动格式和验证的所有编辑控件的方法。
现在我在 OnChange 事件中有使用 TryStrToFloat 方法的代码,但有时我会收到“''不是浮点数”错误。
也许你们比我做得更多,并且有一些很好的例子如何正确地做到这一点。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您想继续使用相同的验证方法,只需增强您的算法以考虑边缘情况(以及您希望如何管理它)。
例如,您可以考虑接受空字符串作为有效输入,并且不抛出异常,或者不抛出异常。您还必须考虑在输入格式错误的情况下如何执行用户交互。例如,如果用户输入无效数字,您希望阻止用户在同一毫秒内输入值......或者您可以采取更自然的方法(例如,进行验证,直到用户认为一切正确)。
您还可以通过在输入完成时以不间断的方式通知用户来管理验证,只需在有问题的字段上产生可见的效果,并在用户尝试时以停止的方式(例如使用消息框)保存数据。
一个简单的验证函数可能如下所示:
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:
只需获取 JVCL 并使用 TJvValidateEdit 组件。
Just get the JVCL and use the TJvValidateEdit component.