如何限制用户在C#文本框中输入小数点后的数字

问题描述:



i有一个接受数字和十进制值的文本框。文本框只允许小数点后一位数。文本框的最大长度为4.



现在当文本框包含.8文本时,如何限制用户在小数点后输入数字(即光标位置紧跟小数点后)。 br />


同时我应该允许小数点前最多两位数



ex:

1.2 ---?有效

12.3 ---->有效

.78 --->无效

.768 --->无效



那么如何设置光标位置以便用户输入小数点前最多两位数当小数点后面有一位数字时(例如.8),限制用户输入小数点后的数字。

Hi,
i have an text box which accepts numeric and decimal values.The text box allows only one digit after the decimal point.Max length of text box is 4.

now when the text box contains a text as ".8", how can i restrict user from entering digits after a decimal point(i.e when cursor position is immediately after the decimal point).

At the same time i should allow max of two digits before the decimal point

ex:
1.2---?valid
12.3---->valid
.78--->invalid
.768--->invalid

So how can i set the cursor position so that it will allow user to enter max of two digits before the decimal point and restrict user from entering digits after the decimal point when there is already a single digit after the decimal point(like ".8").

你可以使用正则表达式检测输入差异,适应这种情况mple:

You can use Regex to detect input discrepancy, adapt from this example:
using System;
using System.Text.RegularExpressions;
public class Program
{
    public static void Main()
    {
        string input = "12.3";

        Regex regex = new Regex(
             "^\\d{0,2}[.]\\d



RegexOptions.IgnoreCase
| RegexOptions.CultureInvariant
| RegexOptions.Compiled
);

if (regex.IsMatch(输入))
{
// 做某事
Console.WriteLine( 有效跨度>);
}
其他
{
// 做其他事情

Console.WriteLine( 不有效的跨度>)!;
}
}
}
", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Compiled ); if (regex.IsMatch(input)) { // do something Console.WriteLine("Valid"); } else { // do other thing Console.WriteLine("Not valid!"); } } }