OneBite.Dev - Coding blog in a bite size

Check If A String Contains Only Alphanumeric Characters In C#

Code snippet for how to Check If A String Contains Only Alphanumeric Characters In C# with sample and detail explanation

Working with strings in any language is crucial and in C#, it’s no different. It’s always a good idea to verify the content of a string especially when it’s from user input. In this mini-article, we will explore how to check if a string contains only alphanumeric characters in C#.

Code snippet for Checking Alphanumeric Characters

using System.Text.RegularExpressions;

public bool CheckStringForAlphaNumericOnly(string testString)
{
    Regex regExpression = new Regex("^[a-zA-Z0-9]*$");
    return regExpression.IsMatch(testString);
}

Code Explanation for Checking Alphanumeric Characters

The above code snippet is a simple C# function named CheckStringForAlphaNumericOnly, which takes a string parameter testString. This function will return true if the testString contains only alphanumeric characters, otherwise, it will return false.

Let’s break it down:

  • The function begins with importing the required namespace System.Text.RegularExpressions. This namespace contains the Regex class for working with Regular expressions.

  • The function CheckStringForAlphaNumericOnly is declared with a string parameter testString.

  • Inside the function, an object regExpression of the Regex class is created with the pattern ”^[a-zA-Z0-9]*$“. This regular expression represents that it will match a string if it contains only alphanumeric characters (a to z, A to Z, 0 to 9).

  • The IsMatch method of the Regex class is then called. It takes testString as a parameter and validates whether the string passed holds to the condition specified in the Regex pattern. If it matches, IsMatch will return true, otherwise false.

Thus, by using this simple method, you can easily verify if a string only contains alphanumeric characters in C#. This validation has multiple applications such as username validation, password validation, etc., where only alphanumeric characters are desirable.

Always remember to scrutinize your data to ensure a higher level of data integrity and to avoid potential security risks. Be sure to key in on these patterns and other best practices in C#. Happy coding!

c-sharp