How to check that string is alphanumeric or not in vb.net and C#

Alphanumeric is a combination of alphabetic and numeric characters.The alphanumeric character set consists of the numbers 0 to 9 and letters A to Z. for example these are the alphanumeric:

1. Author123
2. author5Code
3. 123456TY
4. 897AUTOR
suppose if you want to know that particular string is a alphanumeric or not than you can use following code sample

[VB.Net]

Private Function IsAlphaNum(ByVal strInputText As String) As Boolean
   return System.Text.RegularExpressions.Regex.IsMatch(strInputText, "^[a-zA-Z0-9]+$")
End Function

[C#]

private bool IsAlphaNum(string strInputText)
{
  return System.Text.RegularExpressions.Regex.IsMatch(strInputText, "^[a-zA-Z0-9]+$"); 
}
  • Kris

    This code is horrible, it doesn’t even come close to meeting the goals of this simple function.  For example “123” is not Alpha Numeric?  How about “AA-&^^^%%-12”?

  • graham

    wow just came across this code – ouch

    if you want an alphanumeric checker you need

    // ans – (a)lpha (n)umeric (s)tring is our flag to see if it is or isnt

    dim ans as boolean = true

    For i = 0 To str.Length – 1

    //if you need to include spaces you needto add ‘ or str(i) = ” ” ‘ to the next line – please note that this is not a secure method for cleansing strings just a quick hack around the example!

    If not Char.IsLetter(str(i)) or Char.IsNumber(str(i)) Then

    ans = false

    End If

    Next

    if ans = true
    //yey its alphanumeric
    else
    //boo it isnt
    end if

  • graham

    Ooops – you should also exit the loop

    so after “ans = false”

    put

    “exit for”

    otherwise you are wasting processor time.

  • TheAmes

    Wow this is the worst function ever, seriously this should be deleted, cant believe this pile of crap came up number 1 on google for my search, useless

  • Now we are using the regular expression to check the string is alphanumeric or not..

  • jay

    Be simpler to just return System.Text.RegularExpressions.Regex.IsMatch(strInputText, “^[a-zA-Z0-9]+$”) rather than declaring the variable, initializing it to a value that is never used, and then having an IF.

  • Vishal

    How to validate input.. 1 item string followed by 4 digits