For Asp.Net mvc model validation I'm trying to create a regex for the following requirement:
string length between 1-5 (including 1 and 5 limit)
non word characters are not allowed
underscore not allowed
I can write a regex witch matches the non word characters but not the inverse of my question.
Regex
Non word characters and underscore match:
([\W_])
String length between 1 and 5:
{1-5}
Asp.net mvc Code:
namespace x
{
public class Model
{
[RegularExpression(@"")]
public string AString {get;set;}
}
}
Solutions1
You can use
^[^\W_]{1,5}$
Se the demo
The regex breakdown:
^ - start of string
[^\W_]{1,5} - not a non-word character and not a _ 1 to 5 occurrences
$ - end of string.
The [^...] is a negated character class that matches any character that is not in the character class.
Also, when you want to limit string length with a regex, you need to use some boundaries. In this case, you can rely on the usual start/end-of-string anchors.