SuryaPrakash Kamarthi
SuryaPrakash Kamarthi

Reputation: 25

C# regular Expression that allows only alphabets and numbers but not any special characters or spaces

I need to validate a textbox that should accept strings like 'ab123cd' , 'xy12345', 'a567891'. How can I write a regular expression to meet this requirement? The Length of the accepting string should not exceed 7 characters. Should not allow any Special characters or spaces within the string.

while(textbox.text does not match the requirement)
{
MessageBox.Show("Please enter Valid string");
prompt.ShowDialog();  //displaying a Dialog box that shows a textbox  
}

Also help me writing the code as shown above. Thank You !!

Upvotes: 1

Views: 3031

Answers (2)

Mustofa Rizwan
Mustofa Rizwan

Reputation: 10466

Edit: UPDATED You can try this

^(?=.*[a-zA-Z])(?=.*[0-9])[a-zA-Z0-9]{1,7}$

Explanation:

  1. ^ marks start position
  2. (?=.*[a-zA-Z]) looks ahead to see if there is any alphabet
  3. (?=.*[0-9]) looks ahead to see if there is any number
  4. [a-zA-Z0-9] means any character between a-z , A-Z or 0-9
  5. {1,7} means can only occur 1-7 times
  6. $ marks end of the string

Demo

Upvotes: 2

AFract
AFract

Reputation: 9705

You can use ^\w{1,7}$

Means between one and seven alphanumerical chars. You can easily adjust length limits.

If you prefer a greater control other allowed characters, use : ^[a-zA-Z0-9]{1,7}$, because \w is more permissive so be careful

For C#, you can use the Regex.IsMatch method : Regex.IsMatch méthode (System.Text.RegularExpressions) : https://msdn.microsoft.com/fr-fr/library/system.text.regularexpressions.regex.ismatch(v=vs.110).aspx

Very simple to use.

Upvotes: 1

Related Questions