如何限制用户在文本框中输入多个小数点 [英] How to restrict user from entering more than one decimal point in text box

查看:257
本文介绍了如何限制用户在文本框中输入多个小数点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我有一个只接受数字和小数值的文本框。我使用下面的正则表达式来满足这个条件。




I have an textbox which will accept only numeric and decimal values. i have used the below regular expression to statisfy this condition.

Regex reg = new Regex("[^[0-9.]+");





文本框的最大长度为4.



文本框将接受小数点前最多两位数和小数点后一位数。为了达到这个目的,使用下面的正则表达式:





The max length of the text box is 4.

And the textbox will accept max of two digits before decimal point and single digit after the decimal point.. To achieve this am using the below regex expression:

Regex re = new Regex("^\\d{1,2}([.]\\d{1})$");





这将输出为1.4,12.5等。



所以现在用户输入多个小数点,如12 ..或2 ...如何我应该限制吗?



有人可以帮帮我吗?



代码块a dded [/ edit]



This will give the output as 1.4,12.5 etc..

So now when the user enters more than one decimal point like 12.. or 2... how should i restrict?

can anyone please help me?

[edit]Code block added[/edit]

推荐答案

);





这将输出为1.4,12.5等。



所以现在当用户输入多个小数点时12 ..或2 ...我应该如何限制?



有人可以帮助我吗?



[edit]添加的代码块[/ edit]



This will give the output as 1.4,12.5 etc..

So now when the user enters more than one decimal point like 12.. or 2... how should i restrict?

can anyone please help me?

[edit]Code block added[/edit]


简单的方法是检查每个按键上的小数位数。以下是相同的存根,



Simple way is to check number of Decimal places on each keypress. Following is stub for same,

Private Sub Text1_KeyPress(KeyAscii As Integer)
    If KeyAscii = 46 Then
        If InStr(Text1.Text, ".") > 1 Then
            KeyAscii = 0
        End If
    End If
End Sub





这将限制用户输入两个或更多小数位。现在添加你的逻辑,以防止用户在输入字符串的开头和结尾输入小数位数。



希望这对你有帮助。



This will restrict user from entering two or more decimal places. Now add your logic to prevent user from entering Decimal Places at the start and end of the input string.

Hope this helps you.


如果您在基于Windows窗体的应用程序中执行此操作,请使用 MaskedTextBox 。如果这是基于Web的应用程序,您可以使用Ajax工具包附带的 MaskedEdit 控件。



编辑:由于您使用的是Windows表单,这是一种更好的方法:



If you are doing this in a Windows Form based application, make use of MaskedTextBox. If this is web based application, you can make use of MaskedEdit control that comes with Ajax toolkit.

Since you are using Windows form, this is a better way to do it:

NumericUpDown numericUpDown = new NumericUpDown();
           numericUpDown.Maximum = 99.9M;
           numericUpDown.Minimum = 0.0M;
           numericUpDown.DecimalPlaces = 1;





编辑1:WPF中没有NumericUpDown。您可以从Extended WPF工具包中获取一个或构建您自己的工具包。



Edit 1: There no NumericUpDown in WPF. You can get one from Extended WPF toolkit or build your own.


这篇关于如何限制用户在文本框中输入多个小数点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆