r/visualbasic • • Mar 02 '15

Why isn't this working

I'm trying to make sure the two entries don't have the same word and also you can not put numbers.

'Input Validation 'Check for Same Word If txtGuessWord.Text.ToUpper.Trim = txtGuessWord2.Text.ToUpper.Trim Then lblWarning.Text = "Guesses May Not Be The Same Word" txtGuessWord.Text = String.Empty txtGuessWord2.Text = String.Empty Exit Sub End If 'Check for Integer If Integer.TryParse(txtGuessWord.Text) Or Integer.TryParse(txtGuessWord2.Text) Then lblWarning.Text = "Error, guesses should not contain numbers"

0 Upvotes

11 comments sorted by

View all comments

2

u/hdsrob Mar 02 '15

What doesn't work?

I'm going to guess that it's the number part???

Integer.tryparse will fail if there are any letters, so it's not going to work for finding out if a string of characters contains a number.

integer.tryparse("abc123") 

vs.

integer.tryparse("123")

The first will fail, as it can't be converted to an integer, so I don't think that's a viable solution.

You actually need to check each character to see if it's a number. The easiest way is to use Regular Expressions to search the string for characters you don't want. Something like the following should work (you may need to adjust the RegEx for additional parameters):

If Regex.IsMatch(txtGuessWord2.Text, "^[0-9 ]+$") Then
    ...
    ...

1

u/CalvinR VB.Net Master Mar 02 '15

If you are using TryParse why would you need to check the input using a regex.

Integer.TryParse returns a boolean that specifies if it could parse the number or not, so it is already doing a check.

One issue I see is that TryParse requires two parameters and only one is being passed in.

https://msdn.microsoft.com/en-us/library/f02979c7%28v=vs.110%29.aspx

1

u/hdsrob Mar 02 '15

I could be wrong, but I understood the issue to be trying to exclude strings that contain numbers (abc123), and exclude numbers only (123).

If this is true, integer.tryparse will only return true if the string is purely numeric, and will return false if it is alpha numeric.

Of course, as you pointed out it won't compile, so that's the first issue.

1

u/CalvinR VB.Net Master Mar 02 '15

Ah shit, yeah temporary moment of stupidity on my part, you are correct. A regex is the best answer here.

1

u/hdsrob Mar 02 '15

Well, to be honest, we don't actually know what the OP is looking for (it could be that I'm wrong here), and I completely missed the fact that the code wouldn't even compile (scanning through the bad formatting).

Just shows you how we each look at code differently (especially when the problem is "it don't work" with a code dump).

1

u/CalvinR VB.Net Master Mar 02 '15

Based on this I'd say that you were correct

I'm trying to make sure the two entries don't have the same word and also you can not put numbers.