Click here to Skip to main content
15,888,251 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello,

My requirement is to have a username which is having one underscore and should not allow any special characters.I am using client side validation so pls help me with the correct regex.
eg:john_12john


Thanks in advance..
Posted
Comments
[no name] 24-Sep-12 3:00am    
Hi,

Your question requires a little research, it does not present any problem or issue.

Check out sites like http://txt2re.com/ which help you to generate such regular expressions.

 
Share this answer
 
C#
public bool IsAlphaNumericWithUnderscore(string input)
{
    return Regex.IsMatch(input, "^[a-zA-Z0-9_]+$");
}


or

C#
bool result = input.All(c=>Char.IsLetterOrDigit(c) || c=='_');
 
Share this answer
 
Hi,
C#
Regex rx = new Regex("^[a-zA-Z0-9_]*$");
<pre lang="cs">if (rx.IsMatch(UserName.Text))
                    {
                        Valid = true;
                    }
                    else
                    {
MessageBox.Show("Special characters cannot be submitted as a part of the Username (except Underscore).\nPlease re enter the User name and click Button.");
                        UserName.Text = "";
                        UserName.Focus();
                        return;
                    }


try this code, it may helpful for you
 
Share this answer
 
v4
I use [A-Za-z0-9_] which allows underscore, but blocks all other special characters.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900