wpf 验证用户输入的十进制数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32482771/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 13:24:16  来源:igfitidea点击:

Validating user input of decimal number

c#regexwpf

提问by Ian W

I have a wpf text box and I want to check as the user inputs into it that they are only using 0 1 2 3 4 5 6 7 8 9 . [Decimal Point] characters for decimal numbers. I use this textbox to convert to a decimal later

我有一个 wpf 文本框,我想在用户输入时检查他们是否只使用 0 1 2 3 4 5 6 7 8 9 。[Decimal Point] 十进制数的字符。我稍后使用此文本框转换为小数

I am using the follow articles as a starting point Regex MatchPreview Text Input exampleregex-to-allow-one-decimal-number-or-a-range-of-decimal-number

我使用以下文章作为起点 Regex 匹配预览文本输入示例regex-to-allow-one-decimal-number-or-a-range-of-decimal-number

Here is my xaml

这是我的 xaml

<TextBox Grid.Column="1" Height="28" HorizontalAlignment="Left" Margin="10,10,0,0" Name="tbTaxFreeLimit" Width="90" VerticalAlignment="Top" 
                                             AcceptsTab="True" 
                                             PreviewTextInput="tbDecimalCheck_PreviewTextInput"
                                            />

And c#

和 C#

private void tbDecimalCheck_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
     // Test for decimal
     if (IsNumeric(e.Text)==false)
         e.Handled = true;
}

private bool IsNumeric(string s)
{
    Regex r = new Regex(@"^[0-9]");

    return r.IsMatch(s);
}

This example works fine for 0 1 2 3 4 5 6 7 8 9 but I can not enter the decimal point .

此示例适用于 0 1 2 3 4 5 6 7 8 9 但我无法输入小数点。

If I change the to following code below it has no effect

如果我将下面的代码更改为以下代码则无效

Regex r = new Regex(@"^[0-9].");

回答by Matt Burland

Your regex ^[0-9].is saying from the start of the string match one character in the range 0-9and then match any character (.means any character). That's not what you want. You'd need to match any number of characters, an optional decimal point, and then a bunch more numbers. Something like:

您的正则表达式^[0-9].是说从字符串的开头匹配范围中的一个字符0-9,然后匹配任何字符(.表示任何字符)。那不是你想要的。您需要匹配任意数量的字符、一个可选的小数点,然后是更多的数字。就像是:

^\d+\.?\d*$

Which says 1 or more (+) digit (\dis equivalent to [0-9]), 0 or 1 (?) decimal point (the .has to be escaped to match a literal .hence \.) and then 0 or more (*) digits.

它说1或多个(+)数位(\d等效于[0-9]),0或1( ?)小数点(在.来转义以匹配字面.因此\.),然后0以上(*)数字。

This fixes your regex, but doing this on a text input is kind of a pain and you are better off letting the user enter text and then validating it with something like decimal.TryParserather than trying to restrict while they type. Why? Consider the user enters:

这修复了您的正则表达式,但是在文本输入上执行此操作是一种痛苦,您最好让用户输入文本,然后使用类似的内容对其进行验证,decimal.TryParse而不是在他们键入时尝试限制。为什么?考虑用户输入:

1     // this is valid

And then:

进而:

1.    // this is still valid

And then:

进而:

1.2   // still valid

And then they realize they meant 2.2, so what do they do? They delete the 1to give:

然后他们意识到他们的意思2.2,那他们怎么办?他们删除了1给:

.2     // Buzzzz, not valid

That's really annoying for a user. The user tries to delete the 1and the control stubbornly keeps rejecting the change. Why? The user doesn't know. Don't turn entering user input into a game of "guess what the rules are".

这对用户来说真的很烦人。用户尝试删除1,控件顽固地拒绝更改。为什么?用户不知道。不要将输入用户输入变成“猜猜规则是什么”的游戏。

Another thing to consider, which may or may not be a problem for you, is that not all cultures use .as a decimal separator. In fact most of the world doesn't.

另一件需要考虑的事情(对您来说可能是也可能不是问题)是,并非所有文化都.用作小数点分隔符。事实上,世界上大部分地区都没有

So don't cancel text entry, use TryParse(with appropriate cultural settings) and just set an error on the TextBoxrather than stop user entering text. Just don't let the user go to whatever the next stage is until they resolve the problem with the numeric entry.

所以不要取消文本输入,使用TryParse(使用适当的文化设置)并且只是设置一个错误TextBox而不是停止用户输入文本。在用户解决数字输入问题之前,不要让用户进入下一阶段。

回答by R Day

A regular expression may not be the most readable/maintainable way to do this.

正则表达式可能不是执行此操作的最可读/可维护的方式。

Try parsing it;

尝试解析它;

private bool IsNumeric(string s) => decimal.TryParse(s, out var value);

回答by dgavian

Something like:

就像是:

Regex r = new Regex(@"^\d+\.?\d*$");

Explanation: "^" matches the beginning of the string; \d+ matches one or more digits, \.? matches an optional decimal point, and \d* matches zero or more digits. "$" matches the end of the string.

说明:“^”匹配字符串的开头;\d+ 匹配一位或多位数字,\.? 匹配可选的小数点,\d* 匹配零个或多个数字。"$" 匹配字符串的结尾。

回答by user2662006

System.Text.RegularExpressions.Regex.IsMatch(txtTransactionAmount.Text, @"[^0-9].[^0-9]")