i want to validate the text in a textbox as alphanumeric (a-z, A-Z, 0-9) - is there built in method for this or do I have to loop through the string and chaeck each character?
I am placing the code on the textbox changetext event.
Loading
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Amit ChoudharyRank #145 · 15.8K reputationPosted Apr 13, 2011, 5:02 AM EDT
Use below code to validation your input string in textbox
using System.Text.RegularExpressions;
// Function to Check for AlphaNumeric.
public bool IsAlphaNumeric(String strToCheck)
{
Regex objAlphaNumericPattern=new Regex("[^a-zA-Z0-9]");
return !objAlphaNumericPattern.IsMatch(strToCheck);
}
Hope this helps you.
Thanks.
Richard Brennan89 reputationPosted Apr 13, 2011, 5:17 AM EDT
private void txtChangePasswordUsername_TextChanged(object sender, EventArgs e)
{
string text = txtChangePasswordUsername.Text;
int textLength = text.Length;
for (int i = 0; i < textLength; )
{
if(char.IsLetter(text[i]) || char.IsNumber(text[i]))
i++;
else
{
MessageBox.Show("Enter only letters or numbers.", "Alert!");
txtChangePasswordUsername.Text = "";
txtChangePasswordUsername.Focus();
i = textLength; ß could i use a break statement here?
}
}
}
VulpesRank #55 · 29.2K reputationPosted Apr 13, 2011, 6:31 AM EDT
private void txtChangePasswordUsername_TextChanged(object sender, EventArgs e)
{
bool isValid = true;
foreach(char c in txtChangePasswordUsername.Text)
{
if(!char.IsLetterOrDigit(c))
{
isValid = false;
break;
}
}
if(!isValid)
{
MessageBox.Show("Enter only letters or numbers.", "Alert!");
txtChangePasswordUsername.Text = "";
txtChangePasswordUsername.Focus();
}
}
jitender67 reputationPosted Nov 15, 2013, 10:31 AM EST
Try this one:
public static Boolean isAlphaNumeric(string strToCheck) { Regex rg = new Regex(@"^[a-zA-Z0-9]*$"); return rg.IsMatch(strToCheck); } or this public static Boolean isAlphaNumeric(string strToCheck) { Regex rg = new Regex(@"^[a-zA-Z0-9]+$"); return rg.IsMatch(strToCheck); }In the example above: