VB.NET - TextBox Validation - Asked By Ben Sebuabe on 24-Sep-14 10:06 AM

Please I'm using vb.net 2013 and I have a textbox named txtRecipients

Now i want to check for the following:

1. The phone no. should always start with 233 followed by any          digit other than zero like: 233201245685 
2. Multiple phone numbers should be separated by a comma, like 233201245685, and the comma replaced automatically before the start of another phone number in the same format. So if two phone numbers are entered they should be like this:
233201245685,233547345696 

I did something like this in the leave event. Is there any better way to do this as the comma is not getting replaced at a specific position. I used both the remove and replaced functions, but that did not work. 



  Dim str1 As String = Mid(Me.txtRecipients.Text, 1, 1) 
        Dim str2 As String = Mid(Me.txtRecipients.Text, 2, 1)
        Dim str3 As String = Mid(Me.txtRecipients.Text, 3, 1)
        Dim str4 As String = Mid(Me.txtRecipients.Text, 4, 1)
        Dim str13 As String = Mid(Me.txtRecipients.Text, 13, 1)
        If str1.Trim  2 Then
            Me.txtRecipients.Focus()
            MsgBox(The first digit must be 2)
            Exit Sub
        End If
        If str2.Trim  3 Then
            Me.txtRecipients.Focus()
            MsgBox(The second digit must be 3)
            Exit Sub
        End If
        If str3.Trim  3 Then
            Me.txtRecipients.Focus()
            MsgBox(The third digit must be 3)
            Exit Sub
        End If

        If str4 = 0 Then
            Me.txtRecipients.Text.Replace(0, String.Empty)
            Me.txtRecipients.Focus()
            MsgBox(Phone No. must not start with 0. Format e.g. 233243404804)
            Exit Sub
        End If

        If str13  "," Then
            ' Me.txtRecipients.Text.Replace(str13, ",")
            Me.txtRecipients.Focus()
            MsgBox(Phone No. must not start with 0. Format e.g. 233243404804)
            Exit Sub
        End If

Robbe Morris replied to Ben Sebuabe on 23-Sep-14 04:26 PM
For starters, make this a separate method you can call in multiple places.  Putting validation code in event handlers is bad practice.

For your specific needs, I think you'll have an easier time if you create a loop that evaluates each character in a string and then decide what to do with it.  In your case, it would be something like appending to a string until it reaches a certain condition.  Then, if it meets the right condition, at it to a List<int>, clear your current string builder, and start over with the next character in your master string.

Honestly though, I think I'd work my UI a little differently.  I show a simple textbox where the phone gets added to a list as soon as it meets a certain criteria.  Then, clear outs and lets the user put another one in.  You could always create the comma delimited list on save if you need to save multiple phone numbers that way.