I am trying to add a “RegularExpression” attribute to a property in a ViewModel
[RegularExpression(@"^(?=^.{8,}$)(?=.*\d)(?=.*\W+)(?=.*[a-z])(?=.*[A-Z])(?i-msnx:(?!.*pass|.*password|.*word|.*god|.*\s))(?!^.*\n)^((.))+$.*$", ErrorMessage = "Password does not meet requirements.")]
public string NewPassword { get; set; }
When the validation occurs, I get the following exception from Visual Studio:
Microsoft JScript runtime error: Syntax error in regular expression
This is the same exact regular expression that I am defining in the web.config when defining the Membership provider:
passwordStrengthRegularExpression="^(?=^.{8,}$)(?=.*\d)(?=.*\W+)(?=.*[a-z])(?=.*[A-Z])(?i-msnx:(?!.*pass|.*password|.*word|.*god|.*\s))(?!^.*\n)^((.))+$.*$"
Can someone tell me why I am getting this error when using the regular expression in the Model attribute?
JScript is Microsoft’s version of ECMAScript, which supports an extremely limited set of regex features compared to .NET. Your biggest problem is that it doesn’t support inline modifiers like
(?i:xyz). There also seems to be no way to pass modifiers separately, like you could if you were using C# or JScript directly. If you want to exclude things case-insensitively, you’re kinda screwed.Be aware, too, that character-class shorthands like
\dand\Whave different meanings on the server (.NET) than they do on the client (JScript). If you want the regex to work the same on both sides, you might want to be more specific. Here’s an example, broken down for clarity:As you can see, I’m only excluding all-lowercase or all-uppercase versions of
pass,word, etc., which isn’t really satisfactory. If you really need to exclude or require whole words case-insensitively, you may have to use a different kind of validator.