Strings in Visual Basic

There are several ways to validate a string. In the example below we have a string that should be a Social Security Number. It should have a length of 9 and consist entirely of digits. You could put this code in form load and test various different values for SocSec or add a text box to test. Try enough variations so that you are sure it works.
'Strings: Make sure string is 9 digits
Public Class Form1
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Dim SocSec As String = "111-22-3456" 'this would be some input string
        Dim Digits As String = "0123456789"
        Dim Ch As Char
        SocSec = SocSec.Replace("-", "") 'remove dashes
        Dim OK As Boolean = True 'OK until we find an error
        If SocSec.Length <> 9 Then
            OK = False
        Else
            Dim I As Integer = 0
            While I < 9 And OK
                Ch = SocSec.Substring(I, 1)
                If Not Digits.Contains(Ch) Then
                    OK = False
                End If
                I += 1
            End While
        End If
        Me.Text = OK
    End Sub
End Class

Regular Expressions

Regular expressions can be used to validate strings. Notice that we must import regular expressions. the regular expression "[0-9]{9}" means that there must be exactly 9 characters that are in the set [0-9]. This expression does not allow any dashes.

Imports System.Text.RegularExpressions
Public Class Form1
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Dim SocSec As String = "111223456" 'this would be some input string
        Dim SocSecRegex As Regex = New Regex("[0-9]{9}")
        Dim M As Match = SocSecRegex.Match(SocSec)
        Me.Text = M.ToString = SocSec 'They should be the same if it was accepted
    End Sub
End Class
We could use "[0-9]{3}-{0,1}[0-9]{2}-{0,1}[0-9]{4}" to accept the dashes. This says that there must be 3 digits followed by 0 or 1 dashes, followed by 2 digits, followed by 0 or 1 dashes, followed by 4 digits.

NEXT: Regular Expressions