Link to home
Start Free TrialLog in
Avatar of Brian
BrianFlag for United States of America

asked on

Check if TextBox contains anything other than an integer or comma

I have a VB.net program with a TextBox.  Currently I am checking if the user typed in a space and I alert the user if the box contains a space.  But I want to alert the user if anything other than an integer or comma is entered.  Would there be a simple way to determine if anything other than a integer or comma have been entered?  Here's the code I have for checking if a space was entered...
        If PortBox.Text.Contains(" ") Then
            MsgBox("Port box cannot contain spaces", MsgBoxStyle.Critical, "Port Error")
            Exit Sub
        End If

Open in new window

SOLUTION
Avatar of kaufmed
kaufmed
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Brian

ASKER

I'm assuming that using Regex.IsMatch is the best way to do this, but I can't figure out how to incorporate the comma when using Regex.
Avatar of Brian

ASKER

käµfm³d, yes, but can I add a check for comma to that line of code?
Avatar of Brian

ASKER

Also, I need to figure out if anything other than an integer or comma in the textbox.  I tried using this...
       If Not Regex.IsMatch(PortBox.Text, "^[0-9,]") Then
            MsgBox("Not all integers")
        End If

Open in new window


to see if there is anything other than Integers in the textbox, but of course that only checks if there is a number anyplace within the string, not that all are numbers.
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Brian

ASKER

It even works with commas!  If I have "8,10,15", it still works, which is awesome!  Does this work with commas because of the "+$"?
I don't understand what you mean by "but can I add a check for comma to that line of code". That's exactly what the regex I suggested does, as I elaborated upon within that same comment.
Hi Brian;

This part of the pattern, "^[0-9,]", only checks the very first character in the TextBox and does not check any other. By adding the + sign where I placed it, it will check all the characters in the string and the $ does it to the end.