In this tutorial, I’ll show you how to validate TextBox for Alphabets, Numbers or AlphaNumeric Values. If a TextBox is validated only for Numeric, It should not accept other characters. If its validated for alphabets it should not accept other characters. Its better to make methods for validation.
TextBox can be validated for Alphabets, Numbers and Alphanumeric characters via two methods. (I know there are plenty of methods, but two methods are commonly used)
Method 1
In Method 1 each character is scanned via foreach loop, if it finds any other character it stops looping and returns false.
AlphaNumeric
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
public bool isAlphaNumeric(string text) { foreach (char character in text) { if (!Char.IsLetterOrDigit(character)) { return false; } } if (text.Length == 0) { return false; } return true; } |
Digits
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
public bool isDigits(string text) { foreach (char character in text) { if (!Char.IsDigit(character)) { return false; } } if (text.Length == 0) { return false; } return true; } |
Alphabets
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
public bool isAlphabet(string text) { foreach (char character in text) { if (!Char.IsLetter(character)) { return false; } } if (text.Length == 0) { return false; } return true; } |
Method 2
In Method 2, Regular Expression is used for validation. Namespace that will be used is
1 |
using System.Text.RegularExpressions; |
Alphabets
1 2 3 4 5 |
public bool isAlphabet(string text) { bool isAlphabet = Regex.IsMatch(text, @"^[a-zA-Z]+$"); return isAlphabet; } |
Digits
1 2 3 4 5 |
public bool isDigit(string text) { bool isDigit = Regex.IsMatch(text, @"^[0-9]+$"); return isDigit; } |
AlphaNumeric
1 2 3 4 5 |
public bool isAlphaNumeric(string text) { bool isAlphaNumeric = Regex.IsMatch(text, @"^[a-zA-Z0-9]+$"); return isAlphaNumeric; } |