简体   繁体   English

验证用户输入的十进制数

[英]Validating user input of decimal number

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 . 我有一个wpf文本框,我想检查一下用户输入的内容是否仅使用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 我稍后将使用此文本框转换为小数

I am using the follow articles as a starting point Regex Match Preview Text Input example 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].");

Your regex ^[0-9]. 您的正则表达式^[0-9]. is saying from the start of the string match one character in the range 0-9 and then match any character ( . means any character). 从字符串的开头说匹配0-9范围内的一个字符,然后匹配任何字符( .表示任何字符)。 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: 就像是:

^\d+\.?\d*$

Which says 1 or more ( + ) digit ( \\d is 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.TryParse rather than trying to restrict while they type. 这可以修复您的正则表达式,但是在文本输入上执行此操作很decimal.TryParse最好让用户输入文本,然后使用decimal.TryParse进行验证( decimal.TryParse而不是尝试在键入时进行限制。 Why? 为什么? Consider the user enters: 考虑用户输入:

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? 然后他们意识到它们的意思是2.2 ,所以它们做什么? They delete the 1 to give: 他们删除1给出:

.2     // Buzzzz, not valid

That's really annoying for a user. 对于用户而言,这确实很烦人。 The user tries to delete the 1 and the control stubbornly keeps rejecting the change. 用户尝试删除1并且该控件顽固地拒绝更改。 Why? 为什么? The user doesn't know. 用户不知道。 Don't turn entering user input into a game of "guess what the rules are". 不要将输入的用户输入变成“猜测规则是什么”的游戏。

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 TextBox rather than stop user entering text. 因此,不要取消文本输入,请使用TryParse (具有适当的文化设置),并在TextBox上设置错误,而不是停止用户输入文本。 Just don't let the user go to whatever the next stage is until they resolve the problem with the numeric entry. 只是在解决数字输入问题之前,不要让用户进入下一步。

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);

Something like: 就像是:

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

Explanation: "^" matches the beginning of the string; 说明:“ ^”匹配字符串的开头; \\d+ matches one or more digits, \\.? \\ d +与一个或多个数字匹配。 matches an optional decimal point, and \\d* matches zero or more digits. 匹配可选的小数点,\\ d *匹配零个或多个数字。 "$" matches the end of the string. “ $”匹配字符串的结尾。

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

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

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