restrict String property characters


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")]

Jul 27, 2015 21:43


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.

Jul 27, 2015 22:58

In addition to Grzegorz's post, if you need support for non-English letters (ø, å,æ, etc.), you can use ^[\p{L}\d-]+$

Edited, Jul 28, 2015 9:30

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?

Jul 28, 2015 14:52

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.

Jul 28, 2015 20:38

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! 

Jul 30, 2015 19:40
This topic was created over six months ago and has been resolved. If you have a similar question, please create a new topic and refer to this one.
* You are NOT allowed to include any hyperlinks in the post because your account hasn't associated to your company. User profile should be updated.