Dan Callahan Dan Callahan - 14 days ago 8
Vb.net Question

What's wrong with this if statement?

If this receives "ffff", it immediately resolves to true and displays the message box. The way I'm reading this is "if the text, starting at index (which initializes at zero earlier in the code) and going for a distance of 1 (meaning it only evaluates this single letter) is not either A-Z or a-z, then show this message box. Otherwise, exit this if-statement"

Why is that not what's actually happening?

If (txtPartNum.Text.Substring(index, 1) IsNot "[A-Z]" OrElse txtPartNum.Text.Substring(index, 1) IsNot "[a-z]") Then
MessageBox.Show("Error: Part number must contain two numbers followed by two letters. first")
blnValid = False
End If


Edit: I tried switching to this, and I'm not getting any luck with this, either

If (txtPartNum.Text.Substring(index, 1) Like "[!A-Z]" OrElse txtPartNum.Text.Substring(index, 1) Like "[!a-z]") Then
MessageBox.Show("Error: Part number must contain two numbers followed by two letters. first")
blnValid = False
End If


Edit 2: I made a string to hold txtPartNum.Text.Substring(index, 1), and verified that it is receiving the first letter in the textbox. I also tried removing the "!" in the character pattern, and that had no effect on whether or not it resolved true - it came up as true each time.

Answer

As you have a simple pattern which the input must comply with, you can use a regular expression.

Dim textToLookAt = txtPartNum.Text
If Not (System.Text.RegularExpressions.Regex.IsMatch(textToLookAt, "^[0-9]{2}[A-Za-z]{2}")) Then
    MessageBox.Show("Error: Part number must contain two numbers followed by two letters. first")
    blnValid = False
End If

The ^ means the start of the line. The [0-9] means characters in the range "0" to "9". The {2} means exactly two of the previous item - in this case [0-9]. [A-Za-z] means characters in those ranges. There is nothing to tell the regex that the line must finish there, so any characters after the two digits and two letters are allowed.

Comments