Reputation: 25
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
Reputation: 10466
Edit: UPDATED You can try this
^(?=.*[a-zA-Z])(?=.*[0-9])[a-zA-Z0-9]{1,7}$
Explanation:
^
marks start position(?=.*[a-zA-Z])
looks ahead to see if there is any alphabet(?=.*[0-9]
) looks ahead to see if there is any number[a-zA-Z0-9]
means any character between a-z , A-Z or 0-9{1,7}
means can only occur 1-7 times$
marks end of the stringUpvotes: 2
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