Adapt text validation function to consider selected text
I have this function which evaluates the contents of a textbox (or combobox or maskedtextbox) control and, in conjunction with a KeyPress event, will either allow or disallow the input. It is quite useful for dates or textboxes for which only numeric input is valid. It allows a set number of digits after a single decimal point, if specified in the function call. It also allows the backspace character if the textbox is full.
I would like it to allow me to input what would otherwise be valid text when the textbox is full but one or more characters are highlighted (and would therefore be replaced by the keypress character. Can anyone show me how to do that, please?
''' <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 = Fa开发者_如何转开发lse 'allow Backspace
Return returnValue
End Function
You can add a couple of parameters (intLengthOfHighlightedText and intLengthOfControl) and pass Textbox.SelectedText and TextboxName.MaxLength (assuming single line text control). Then just work that out in your function. Otherwise you can pass the value of the whole textbox control (make it overloaded or do the work for the combobox, etc).
精彩评论