【发布时间】:2010-06-04 00:31:20
【问题描述】:
我有这个函数,它评估文本框(或组合框或掩码文本框)控件的内容,并结合 KeyPress 事件,将允许或禁止输入。它对于只有数字输入有效的日期或文本框非常有用。如果在函数调用中指定,它允许在单个小数点后设置一组数字。如果文本框已满,它还允许退格字符。
我希望它允许我在文本框已满但突出显示一个或多个字符时输入有效文本(因此将被按键字符替换。谁能告诉我如何做到这一点,请问?
''' <summary>
''' Validates that input is numeric.
''' Allows one decimal place unless intDecimal is less than 1
''' Will allow a set number of numbers after the decimal place.
''' </summary>
''' <param name="strKeyPress">The key which has been pressed</param>
''' <param name="strText">Current text of the textbox</param>
''' <param name="intPosition">Current cursor position in textbox</param>
''' <param name="intDecimal">Number of decimal places desired.</param>
''' <returns>Boolean: true means that input is numeric, false means it is not.</returns>
''' <remarks>Used with a keypress event to validate input. Do not handle input if function returns false.</remarks>
Public Function InputIsNumeric(ByVal strKeyPress As String, ByVal strText As String, ByVal intPosition As Integer, ByVal intDecimal As Integer) As Boolean
Dim dot As Integer
Dim ch As String
Dim returnValue As Boolean
If Not Char.IsDigit(CType(strKeyPress, Char)) Then returnValue = True
If strKeyPress = "-" And intPosition = 0 Then returnValue = False 'allow negative number
If strKeyPress = "." And strText.IndexOf(".") = -1 And intDecimal > 0 Then returnValue = False 'allow single decimal point
dot = strText.IndexOf(".")
If dot > -1 Then 'limit to set decimal places
ch = strText.Substring(dot + 1)
If ch.Length > (intDecimal - 1) Then returnValue = True
End If
If strKeyPress = Chr(8) Then returnValue = False 'allow Backspace
Return returnValue
End Function
【问题讨论】:
标签: .net vb.net validation