Hi,
If you use \w, then also the underscore character will be allowed. If it's ok then you could use: ^(\w|-)+$
If not, then you need to be more specific and set: ^([a-z]|[A-Z]|[0-9]|-)+$
To limit the length use {min, max} convention
The final code: ^([a-z]|[A-Z]|[0-9]|-){1,100}$
Link to fiddle.
In addition to Grzegorz's post, if you need support for non-English letters (ø, å,æ, etc.), you can use ^[\p{L}\d-]+$
Thanks for the responses but it's not working for me. This is what I have on the property I want to check...
[RegularExpression("^(\w|-)+$", ErrorMessage = "ID Cannot contain spaces")]
VS says there is an unrecognized escape sequence. Any thoughts on what I'm doing wrong?
I think that you should escape the "\". You could do this in two ways:
- by doubling "\" character [RegularExpression("^(\\w|-)+$", ErrorMessage = "ID Cannot contain spaces")]
- or using "@" before string constant: [RegularExpression(@"^(\w|-)+$", ErrorMessage = "ID Cannot contain spaces")]
The code should compile now.
If you see my original post, I started off trying the @ symbol but that wasn't working. When I put in the double \ it does. Maybe I was doing something else wrong in the beginning. Either way, thank you for your help Grzegorz!
I'm wanting to restrict a string property to only allow letters, digits, and dashes - no spaces. I have tried several variations with no success. Here's my latest. I'm not a regex or Epi expert so any advice or answers to my problem would be great!
[RegularExpression(@"^(\w|\d|-)$", ErrorMessage = "ID Cannot contain spaces")]