简体   繁体   English

文本框十进制验证 - 省略点

[英]Textbox decimal validation - omit dots

I'm doing a validation on TextBox where user must enter valid decimal text.我正在对用户必须输入有效十进制文本的 TextBox 进行验证。 Decimal represents amount of money.十进制代表金额。

Some examples of correct inputs:正确输入的一些示例:

1
1.000,99
1,99
1.000.000,99 etc.

Some examples of non-valid inputs:无效输入的一些示例:

1.0.0.0.0.
1.......0.0.0. etc.

Here is my validation code with TryParse method which I thought would solve everything:这是我使用 TryParse 方法的验证代码,我认为它可以解决所有问题:

   public void Validate_amount(string property_name, string string_value)
   {
        DeleteErrors(property_name);

        if (string.IsNullOrEmpty(string_value))//Ignore empty text
        {
            return;
        }
 
        bool is_amount = decimal.TryParse(string_value, out decimal n);
          
        if (!is_amount)
        {
            AddError(property_name, "Amount not correct");
            SystemSounds.Beep.Play();
        }
   }

Problem with this approach is that even examples of non-valid inputs are returned as True by TryParse method.这种方法的问题在于,即使是无效输入的示例也会被 TryParse 方法返回为 True。

I can write as many of dots I like, and TryParse will allways return true.我可以写尽可能多的点,并且 TryParse 将始终返回 true。 Comma however works as expected - only one is allowed.然而,逗号按预期工作 - 只允许使用一个。

How to fix this?如何解决这个问题?

The TryParse method has a complete signature like this: TryParse (String, NumberStyles, IFormatProvider, Decimal) . TryParse 方法具有这样的完整签名: TryParse (String, NumberStyles, IFormatProvider, Decimal)

When you do not specify the 2nd and 3rd parameters, the default value is used for them.当您不指定第 2 和第 3 参数时,它们使用默认值。
For your example, the complete call will look like this:对于您的示例,完整的调用将如下所示:

bool is_amount = decimal.TryParse(
    string_value, 
    NumberStyles.Number, 
    NumberFormatInfo.CurrentInfo, 
    out decimal n);

The number of digits in groups is set in the NumberFormatInfo.CurrentInfo.CurrencyGroupSizes property (int []).组中的位数在 NumberFormatInfo.CurrentInfo.CurrencyGroupSizes 属性 (int []) 中设置。
And it depends on the OS settings.这取决于操作系统设置。
Let's say, on my computer, your incorrect examples all return false.比方说,在我的电脑上,你不正确的例子都返回 false。

You can make a copy of the current value, change the properties you need and pass this instance to TryParse:您可以复制当前值,更改您需要的属性并将此实例传递给 TryParse:

string string_value = "1.0.0.0.0.";

NumberFormatInfo numberFormatInfo = (NumberFormatInfo) NumberFormatInfo.CurrentInfo.Clone();

Debug.WriteLine(string.Join(", ", numberFormatInfo.CurrencyGroupSizes));

numberFormatInfo.CurrencyGroupSizes = new int[] { 3 };

Debug.WriteLine(decimal.TryParse(string_value, NumberStyles.Number, numberFormatInfo, out decimal number));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM