November Happy Hour will be moved to Thursday December 5th.

restrict String property characters

Vote:
 

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

#131463
Jul 27, 2015 21:43
Vote:
 

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.

#131465
Jul 27, 2015 22:58
Vote:
 

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

#131468
Edited, Jul 28, 2015 9:30
Vote:
 

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?

#131486
Jul 28, 2015 14:52
Vote:
 

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.

#131496
Jul 28, 2015 20:38
Vote:
 

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! 

#131604
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.