Reputation: 1651
Hi I have this code
[RegularExpression(@"^[.\\\\/:*?\" + "<>" + "|]?[\\\\/:*?\"<>|]*",
ErrorMessage = "Title must not contain any special characters")]
I want it so the string is not able to have any special character in apart from spaces but I'm not sure why this isn't working?
EDIT:
To confirm, the form won't submit with the string input of: nospecialcharacters
The error message appeard regardless if there are special characters or not.
Upvotes: 3
Views: 1459
Reputation: 966
I also wanted to make validation which would eliminate characters, which are not allowed in Windows file and folder names.
Since I use a language which uses some "special" characters, like Š,Č and Ž, the above answer did not work for me. The "^[\w ]+$"
treats these letters like special characters.
After an extensive search I couldn't find the correct answer.
Finally I solved my problem like so:
[RegularExpression(@"[^|\\/:*?\u0022<>|]+$", ErrorMessage = "Title must not contain any special characters")]
The \u0022
represents ".
I had some problems forming this string. I tried so:
@"[^|\\/:*?\"<>|]+"
but the " ended my string in the middle"[^|\\/:*?\"<>|]+"
but this ignored backslash \Upvotes: 1
Reputation: 25231
I can't really make sense of your current regex but bear in mind that this attribute specifies that the property must match the regular expression (not that it must not match it). So, if you don't want any special characters, you need to specify that the property matches the following pattern:
Something like this ought to do it:
"^[\w ]+$"
Add any other allowed characters (e.g. dashes) into the square brackets.
You may also be able to omit the ^
and $
characters as I believe these are included implicitly; I find it's better to be explicit about these things, though.
Upvotes: 0