Reputation: 597
I can't figure out why this regular expression doesn't work the way I want it to. I want it to allow something like this: "Test123#%&*- Test"
[RegularExpression("[^a-zA-Z0-9/#%&*\\- ]")]
The MSDN documentation only gives one example...
[RegularExpression(@"^[a-zA-Z''-'\s]{1,40}$")]
I don't want to limit input to any specific character length, which the MSDN example does do. I have used this regex pattern with the Regex
object in .net and it works just fine. Why would the DataAnnotations
work differently?
Upvotes: 0
Views: 897
Reputation: 1626
Regex DataAnnotations is written in a way to find what is valid, rather than finding what is invalid. You WANT to match with valid values.
I'd drop your carrot (^). This will allow each individual character you supply to be validated. If anything fails, you'll generate your error message.
Upvotes: 0
Reputation: 92976
I think your way of using a negated class to find not allowed characters is wrong. I can't find a documentation to prove it, but it seems logical to me.
I think you need to give a pattern that matches the allowed input.
Try
[RegularExpression("^[a-zA-Z0-9/#%&*\\- ]*$")]
The *
quantifier makes it repeat the character class 0 or more times. This allows also the empty string! If you don't want the empty string use the quantifier +
, that would be one or more.
*
is a shortcut for {0,}
. if you omit the second number it means there is no maximum match
+
is a shortcut for {1,}
.
Upvotes: 1