验证货币金额
我需要接受仅有效金额的值。该应用程序支持多个区域设置,因此我需要接受以下格式的金额:
10.05 或 10,05 (在某些区域设置中,逗号用于小数分隔符)
它不应该接受 10.456 或 10,456 等值
用户不允许输入美元等符号、英镑或欧元。也不允许使用逗号分隔符(千、百万、十亿等)。此外,不允许出现负数或零值金额。
是否有内置的 .NET 方法来验证这一点?使用正则表达式很困难,因为我需要根据区域设置允许使用逗号或点作为小数分隔符。
I need to accept values which are valid amounts only. The application supports multiple locales so I need to accept amounts in the following formats:
10.05 or 10,05 (in some locale comma is used for decimal separator)
It should not accept values like 10.456 or 10,456
Users are not allowed to enter symbols like dollar, pound or euro. Also no comma separators allowed (for thousands, millions, billions, etc.). Also, no negatives amounts or zero value amounts are allowed.
Is there a built in .NET method to validate this? It is difficult to use regular expression as I need to allow either comma or dot for decimal separator based on the locale.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
看一下带有多个参数的 double.TryParse 函数,特别是
NumberFormats
枚举。如果您指定正确的区域性,它可以处理逗号与小数点的问题。我认为你需要单独处理负/零问题。Take a look at the
double.TryParse
function that takes multiple parameters and in particular theNumberFormats
enumeration. If you are specifying the correct culture, it can handle the comma versus decimal issue. I think you'll need tohandle the negative/zero issue separately though.我会执行以下操作:
将 , 替换为 .
如果 的位置为 .在字符串 <比 stringlength-2 -> 不被接受
解析为双精度,如果失败 ->不接受
I would do the following:
replace , with .
if position of . in string < than stringlength-2 -> not accepted
parse to double, if fails -> not accepted
我知道您提到不使用正则表达式,但您对逗号或句点的要求似乎非常简单。这样的事情行不通吗?
它匹配多个前导数字,检查句点或逗号,然后仅匹配 2 个尾随数字。
I know you mentioned not using a RegEx, but it seems like the requirements you have regarding the comma or period are pretty simple. Wouldn't something like this work?
It matches multiple leading digits, checks for either a period OR comma, and then matches only 2 trailing digits.
使用double.TryParse。它可以处理你想要的一切。您可以提供一组自定义的 NumberStyles 以及自定义 FormatProvider(如果不符合您的需求)。
Use double.TryParse. It handles everything you want. You can provide a custom set of NumberStyles as well as a custom FormatProvider, if non fits your needs.
假设您使用的是 Asp.Net,请尝试 CompareValidator 。您可以将 Type 属性设置为货币。如果将
Operator
属性设置为ValidationCompareOperator.DataTypeCheck
,则CompareValidator
控件会忽略ControlToCompare
和ValueToCompare
属性,仅指示输入到输入控件中的值是否可以转换为 Type 属性指定的数据类型。Assuming you are using Asp.Net, try the CompareValidator. You can set the Type property to currency. If you set the
Operator
property toValidationCompareOperator.DataTypeCheck
, theCompareValidator
control ignores both theControlToCompare
andValueToCompare
properties and simply indicates whether the value entered into the input control can be converted to the data type specified by the Type property.