如何验证dotnet core 2中的货币独立于文化

问题描述 投票:0回答:1

对于一个项目,我需要验证货币。要求是:

12有效12.1有效12.12也有效12.123无效。

现在我可以使用正则表达式来验证这个[RegularExpression(@"^(?!0\.00)\d{1,3}(.\d{3})*(\,\d\d)?$", ErrorMessage = "Must be a currency with no more then 2 digits after the." )]

但是在测试中,当有人使用另一个系统时它会失败。所以在荷兰我们使用12,00并且验证但是在美国和英国他们使用12.00并且没有验证

我也可以使用这样的验证:

float num;
bool isValid = float.TryParse(str, NumberStyles.Currency,CultureInfo.GetCultureInfo("en-US"), // cached

out num);

但后来我无法测试数字后面只有2个数字。

我可以设置一种文化,但是这很奇怪,例如输入2.45的数量,他们习惯于2,45

有人知道如何使验证工作。

问候,

鲁洛夫

.net validation currency
1个回答
1
投票

您可以这样解析货币:

decimal currency = decimal.Parse("123.456", NumberStyles.Currency, CultureInfo.GetCultureInfo("en-US"));

如果你不想在点后接受三个位置,你有两种方法:

如果需要浮点数,则可以转换小数结果。

© www.soinside.com 2019 - 2024. All rights reserved.