Is there an isAlpha function in VB.NET

Viewed 4307

I have a variable to hold an id

Dim empId as String

So the format for a valid ID is:

'the first character should be a letter [A-Z]
'the rest of the string are digits e.g M2895 would be a valid id

I would like to check each of those characters to see if they fit the correct ID

So far, I have come across the isNumeric() function. Is there a similar function in VB.NET to check if a character is a string or alpha character?

3 Answers

You can use RegularExpressions instead of checking each character of your string by hand:

Dim empId as String = "M2895"
If Regex.IsMatch(empId, "^[A-Z]{1}[0-9]+$") Then
    Console.WriteLine("Is valid ID")
End If

If you need a function isAlpha you can create this function by using RegularExpressions too:

Private Function isAlpha(ByVal letterChar As String) As Boolean
    Return Regex.IsMatch(letterChar, "^[A-Z]{1}$")
End Function

For completion, to support estonian alphabet too, you can use the following:

Dim empId as String = "Š2859"
If Regex.IsMatch(empId, "^[^\W\d_]{1}[0-9]+$") Then
    Console.WriteLine("Is valid ID")
End If

You can use functions which works for all Unicode characters

Char.IsLetter Method (String, Int32)
Indicates whether the character at the specified position in a specified string is categorized as a Unicode letter.

Char.IsDigit Method (Char)
Indicates whether the specified Unicode character is categorized as a decimal digit.

So you end up with validation like

Public Function IsValid(id As String)
    If Char.IsLetter(id, 0) = False Then
        Return False
    End If

    If id.Skip(1).All(Char.IsDigit) = False Then
        Return False
    End If   

    Return True   
End Function

Here is my take an isAlpha function, answering the title of this question:

Public Shared Function isAlpha(ByVal s as String) as Boolean
    if s is Nothing then return False
    For Each c As Char in s
        If not Char.IsLetter(c) then return False
    Next
    return True
End Function

However, to answer the body of the question, here is my mod of @Fabio's answer:

Public Function isMyAlphaCode(id As String) as Boolean
    if id is Nothing then return False
    if id.length < 2 then return False
    If Char.IsLetter(id, 0) Then
        Return False
    End If

    If id.Skip(1).All(Char.IsDigit) Then
        Return False
    End If   

    Return True   
End Function
Related