Validating the format of a userform textbox entry - validation

I have a UserForm for a database data extractor I'm making. In it there is a TextBox for typing in the part number that the user wants to extract data for. I want to validate that the user has entered the correct format of part number before the bulk of the extractor runs. To do this I need a code to validate that the text is entered in the specific format:
3 Numeric Characters
1 Alphabetic Character or 1 Hyphon
then 5 Numeric Characters
I tried the following validations at first:
'validate that box is not empty
If TextBox1.Value = "" Then
MsgBox ("Sorry, you need to provide an Amount")
TextBox1.SetFocus
Exit Sub
End If
'validate that box is numeric
If Not IsNumeric(TextBox1.Value) Then
MsgBox ("Sorry, must enter a numer")
TextBox1.SetFocus
Exit Sub
End If
But then I realised that I had the problem that there may be an alphabetic char or hyphon in the fourth position.
I would appreciate any suggestions.
Thanks in advance.

A beginner way to check this input is to just chop up the input string and compare the parts as needed:
Const alpha as String = "abcdefghijklmnopqrstuvwxyz-"
Dim strValue as String
Dim msg as String
strValue = TextBox1.Value
'Make sure it's the right LENGTH
If Len(strValue) <> 9 Then
msg = "Please enter the ID as 3 numeric, 1 alpha/hyphen, 5 numeric"
GoTo EarlyExit
End If
'Check the first three for numeric:
If Not IsNumeric(Left(strValue), 3) Then
msg = "The first three characters should be numeric"
GoTo EarlyExit
End If
'Check the middle character, assuming case not sensitive:
If Instr(1, alpha, Lcase(Mid(strValue, 4, 1)) = 0 Then
msg = "The fourth character should be hyphen or alphabet"
GoTo EarlyExit
End If
'Check the last four characters
If Not IsNumeric(Right(strValue, 4)) Then
msg = "The last four characters should be numeric"
GoTo EarlyExit
End If
'If you've gotten here, then the input is validated:
Exit Sub
EarlyExit:
MsgBox msg
TextBox1.SetFocus
End Sub
3 Numeric Characters 1 Alphabetic Character or 1 Hyphon then 5 Numeric Characters

Related

VB Control Naming by Variable

Dim LineNo as Integer
LineNo = CStr(channel) 'This can have a value of 1 to 100
If LineNo = 1 then
Text1.Text = "Line one selected"
Elseif LineNo = 2 then
Text2.Text = "Line one selected"
'Etc etc
End if
I need to replace the number "1" in Text1.Text and every other TextBox with the value of LineNo? For example:
Text{LineNo}.Text
So I would not have to do a repeated "If" and have a smaller one line code like this:
Text{LineNo}.Text = "Line " & LineNo & " selected"
How would I do this?
Look into a Control array of text boxes. You could have txtLine(), for example, indexed by the channel number.
LineNo = CStr(channel)
txtLine(channel).Text = "Line " & LineNo & " selected"
To create the array, set the Index property of each of the text boxes to an increasing integer, starting at 0.
If you have a finite and relatively small number, you can use a property. I've used this approach with up to 30+ elements in a pinch. Super simple, easy pattern to recognize and replicate in other places. A bit if a pain if the number of elements changes in the future, but extensible nevertheless.
It uses the Choose statement, which takes an index N and returns the Nth element (1-based), hence, the check makes sure that N is > 0 and <= MAX (which you would configure).
Public Property Get TextBox txt(ByVal N As Long)
Const MAX As Long = 10
If N <= 0 || N > MAX Then Exit Property ' Will return a "Nothing". You could return the bound element if you prefer
set txt = Choose(Text1, Text2, Text3, Text4, Text5, Text6, Text7, Text8, Text9, Text10)
End Property
Then, you can simply reference them with the Property, much like an alias:
txt(1).Text = "Line 1 text"
txt(2).Text = "Line 2 text"
If you have an arbitrary number, then you are likely using a control array already, which is simpler because it can be referenced by Index already, so you can directly reference it.
If neither of these work for you and you have a very large number of controls, you can scan the Controls collection in a similar Property, attempting to match ctrl.Name with the pattern of your choice (e.g., matching the first 4 characters to the string "Text", thus matching Text1, Text2, etc, for an unlimited number). Theoretically, this should be future-proofed, but that's just theoretical, because anything can happen. What it does do for you is to encapsulate the lookup in a way that "pretends" to be a control array. Same syntax, just you control the value.
Public Property Get TextBox txt(ByVal N As Long)
Dim I As Long
For I = 0 To Controls.Count - 1 ' Controls is zero-based
' Perform whatever check you need to. Obviously, if you have a "Label" named
' "Text38", the assignment will throw an error (`TextBox = Label` doesn't work).
If Left(Controls(I).Name, 4) = "Text" Then
set txt = Controls(I)
End If
Next
' If you want the Property to never return null, you could uncomment the following line (preventing dereference errors if you insist on the `.Text` for setting/getting the value):
' If txt Is Nothing Then Set txt = Text1
End Property
Use the same way as above: txt(n).Text = "..."

having trouble validating input. need to verify that there is at least 1 numeric char and 1 alpha char

As stated in description, I need to validate user input to make sure it is a minimum of 6 characters long and contains 1 numeric character and 1 character from the alphabet.
So far, I've gotten the length validation working but cannot seem to get my numeric validation to function properly. If I enter nothing but numbers, it works, but if I put letters in IE abc123 it will not recognize that there are numbers present.
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If txtPassword.TextLength < 6 Then
lblError.Text = "Sorry that password is too short."
ElseIf txtPassword.TextLength >= 6 Then
Dim intCheck As Integer = 0
Integer.TryParse(txtPassword.Text, intCheck)
If Integer.TryParse(txtPassword.Text, intCheck) Then
lblError.Text = "Password set!"
Else
lblError.Text = "Password contains no numeric characters"
End If
End If
End Sub
End Class
how about a regular expression?
using System.Text.RegularExpressions;
private static bool CheckAlphaNumeric(string str)   {
return Regex.Match(str.Trim(), #"^[a-zA-Z0-9]*$").Success;  
}
of if you just up to validating a complex password, then this will do it.
-Must be at least 6 characters
-Must contain at least one one lower case letter,
-One upper case letter,
-One digit and one special character
-Valid special characters are – ##$%^&+=
Dim MatchNumberPattern As String = "^.*(?=.{6,})(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[##$%^&+=]).*$"
If txtPasswordText.Trim <> "" Then
If Not Regex.IsMatch(txtPassword.Text, MatchNumberPattern) Then
MessageBox.Show("Password is not valid")
End If
End If
You may want to use regex to validate if the input contains upper/lower case alpha chars, numbers, special chars.

reading between two values

I have to read between 2 values after asking the users if he want between the '' or not between.
Exemple if the user select 1 in the text
'Hi' My name is 'Kev'in and i'm happ'y' to be 'there'
he will have
'Hi' 'Kev' 'y' 'there'
in a text file. If he chose 2, he will have
My name is in and i'm happ to be
Right now I'm using
Do While objScriptFile.AtEndOfStream <> True
strCurrentLine = objScriptFile.ReadLine
intIsComment = InStr(1,strCurrentLine,"'")
If intIsComment > 0 Then
objCommentFile.Write strCurrentLine & vbCrLf
End If
Loop
Else
For now it's only reading both of the value (between '' and not between) but I have no idea how to change it.
That's pretty simple, provided the delimiter is unique. Split the line at ' and output either the even or the odd array elements, depending on whether 1 or 2 was chosen.
...
strCurrentLine = "'Hi' My name is 'Kev'in and i`m happ'y' to be 'there'"
arr = Split(strCurrentLine, "'")
For i = choice To UBound(arr) Step 2
objCommentFile.Write arr(i)
Next
...
The value of choice is your users' selection (either 1 or 2).
Note that for this to work the strings must not contain apostrophes anywhere else. As #Ekkehard.Horner pointed out in his comment you can't use the delimiter character elsewhere in the text (i'm), because otherwise it would be impossible to distinguish where it was intended to be a delimiter and where not.

"Expected End of Statement" in Loop

I am getting an "expected end of statement" error at line 26, the third to last line. If you look at the code, it is a simple game that has one person enter a word, the script replaces all consonants with underscores, and the second player has to guess the word. Line 26 is, I think, the only thing wrong with this program.
phrase=inputbox("Player 1: Enter a phrase","Guessing Game")
phrase=answer
phrase=Replace(phrase,"A","_")
phrase=Replace(phrase,"B","_")
phrase=Replace(phrase,"C","_")
phrase=Replace(phrase,"D","_")
phrase=Replace(phrase,"F","_")
phrase=Replace(phrase,"G","_")
phrase=Replace(phrase,"H","_")
phrase=Replace(phrase,"J","_")
phrase=Replace(phrase,"K","_")
phrase=Replace(phrase,"L","_")
phrase=Replace(phrase,"M","_")
phrase=Replace(phrase,"N","_")
phrase=Replace(phrase,"P","_")
phrase=Replace(phrase,"Q","_")
phrase=Replace(phrase,"R","_")
phrase=Replace(phrase,"S","_")
phrase=Replace(phrase,"T","_")
phrase=Replace(phrase,"V","_")
phrase=Replace(phrase,"W","_")
phrase=Replace(phrase,"X","_")
phrase=Replace(phrase,"Y","_")
phrase=Replace(phrase,"Z","_")
Do
result=InputBox "Player 2 enter your guess for" & phrase , "Guessing Game"
Loop until result==answer
msgbox "You got it!",vbokonly,"Guessing Game"
In VBScript, the 'equal' comparison operator is =. So change
Loop until result==answer
==>
Loop until result = answer
You're getting that error, because you used a function in an assignment without putting its parameter list in parentheses. Change this line:
result=InputBox "Player 2 enter your guess for" & phrase , "Guessing Game"
into this:
result=InputBox("Player 2 enter your guess for" & phrase , "Guessing Game")
This is one of VBScript's gotchas: depending on where/how you call a procedure or function, you must or mustn't put the parameter list in parentheses.
>>> String 3, "*" 'must not use parentheses here
>>> String(3, "*")
Cannot use parentheses when calling a Sub (0x414)
>>> Call String(3, "*") 'must use parentheses here
>>> Call String 3, "*"
Expected end of statement (0x401)
>>> v = String(3, "*") 'must use parentheses here either
>>> v = String 3, "*"
Expected end of statement (0x401)
To make matters worse, there are situations where parentheses can be used anyway, because they have a different meaning in that context:
>>> Hour(Now)
This actually works, because here the parentheses do not mean "parameter list", but "pass this argument by value". Take a look this article about the many interesting situations parentheses can create in VBScript.
The other mistake in your script, as Ekkehard.Horner already pointed out, is that you use == instead of = for comparing values.
As a side note: you seem to assume that the input will always consist of uppercase letters only, but you never enforce that anywhere. You may want to UCase your input or add a check to validate the input.
Seeing jmvp do such a good job optimizing your program made me want to do the same! :)
Here's my version. I added a constant to specify the application name (since it's used a few times) and also allow player 2 to quit playing by clicking Cancel (or entering nothing).
Const APP_TITLE = "Guessing Game"
strPhrase = InputBox("Player 1: Enter a phrase", APP_TITLE)
With New RegExp
.Pattern = "[^AEIOU]"
.Global = True
strDisplay = .Replace(strPhrase, "_")
End With
Do
strResult = InputBox("Player 2: Enter your guess for " & strDisplay, APP_TITLE)
Loop Until StrComp(strPhrase, strResult, vbBinaryCompare) = 0 Or Len(strResult) = 0
If Len(strResult) > 0 Then MsgBox "You got it!", vbOkOnly, APP_TITLE
Dim phrase As String = InputBox("Player 1: Enter a phrase", "Guessing Game")
Dim charCount As Integer = phrase.Length
Dim strMask As String = vbEmpty
For x = 1 To charCount
strMask &= "_"
Next
Dim guess As String = vbEmpty
Do
guess = InputBox("Player 2 enter your guess for " & strMask, "Guessing Game")
Loop Until phrase = guess
MsgBox("You got it!", vbOKOnly, "Guessing Game")

How to limit the value of the textbox in vb 6.0

I am doing a marks updating database system. I need to limit each of my textbox to be in the value of less than 100, when its over than 100 or when its not number, a message box will pop up and the data won't be save until the user change the mistake. How can I do it?
I agree with Hiren Pandya, but I thought I would add my own take as well.
Be aware that converting a string to a numerical value is not trivial, but the Val, CInt, CDBl etc. functions in VB6 can all give you behavior that close to what you want. (some of those links are for VB.Net, but can still be valuable). You want to make sure you are thinking about digit grouping, positive/negative, decimal separators, etc. when you are validating user input on your own. Most of the time, the built-in functions are good enough.
Private Sub Text1_Change()
On Error GoTo Err_Handler
Dim text As String
text = Text1.text
If IsNumeric(text) = True Then
'If you only want integers...
Dim value As Integer
value = Val(text)
If value <= 100 And value > 0 Then
'The value is good so whatever stuff you need to do
'And then leave the procedure
Exit Sub
End If
End If
'Let everything else fall through here...
Err_Handler:
MsgBox "Invalid input."
'Other stuff to prevent saving
End Sub
In the properties of the text box, set MaxLength to 2.
If you want a message, in the text box Change event, you could do...
If Len(txtBox.Text)>2 then msgbox...
then add your message in the messagebox.
I could go into more detail if you need it. Some thing like below...
Private Sub Text1_Change()
If Len(Text1) > 6 Then
Text1 = " "
MsgBox "Not more than six"
Text1.SetFocus
End If
End Sub

Resources