Text Validation
Hi,
I wonder if anyone can tell me a script that allows me to set a certain criteria for an input box. The input must be able to accept letters in either case and any numbers. I would like an error message to be generated if any other characters such as , $ and & are entered, also if less than 3 characters are entered.
Help would be much appreciated,
Kind Regards,
Joe.
[398 byte] By [
joejdx] at [2007-11-11 8:09:21]

# 1 Re: Text Validation
If you're using the InputBox function, what you see is what you get; there's no way to validate input. If you're using a standard textbox, you can use the Change event to delete unwanted characters:
Private Sub txtBox_Change()
Dim pos As Integer
Static bIgnore As Boolean
' Don't run this code if Change event
' was triggered by our changes
If Not bIgnore Then
bIgnore = True
With txtBox
' Save cursor position
pos = .SelStart
' Replace invalid characters
.Text = RegExReplace(.Text, "[^A-Z0-9]", vbNullString, True)
' Reset cursor position
.SelStart = pos
End With
Else
bIgnore = False
End If
End Sub
' Requires reference to Microsoft VBScript Regular Expressions library
Function RegExReplace(ByVal strOriginalString As String, ByVal strPattern As String, _
ByVal strReplacement As String, ByVal bIgnoreCase As Boolean)
Dim objRegExp As RegExp
Set objRegExp = New RegExp
With objRegExp
.Pattern = strPattern
.IgnoreCase = bIgnoreCase
.Global = True
RegExReplace = .Replace(strOriginalString, strReplacement)
End With
End Function
You can add code to the textbox's Validate event to ensure that the length of the .Text property is at least 3 (Len(txtBox.Text) >= 3).
# 2 Re: Text Validation
Hi Phil,
I managed to validate the input of integers such that only a number can be entered:
rate = Val(InputBox("Plese enter the transfer rate in Mbps"))
While rate <= 0 'ensures user enters a valid transfer rate for the calculation
MsgBox "You have entered an incorrect value, please enter a number greater than zero in Mbps"
rate = Val(InputBox("Plese enter the transfer rate in Mbps"))
Wend 'Loops until value is valid
If rate > 0 Then
rate = rate
End If
This works perfectly and I thought there would be a simpler way to continually loop the input box until the data entered is valid for text and numbers.
Joe.
joejdx at 2007-11-11 17:27:01 >
