Christophe De Troyer
Christophe De Troyer

Reputation: 2922

Model Validation Regex never matches

I have the following Regex annotation:

    [RegularExpression(@"(?=.{6,})(?=(.*\d){1,})(?=(.*\W){1,})", ErrorMessage = "Password is not strong enough!")]
    public string Password { get; set; }

This is a copy/paste from my Regex I use in my MembershipProvider, where it works, as I can register with passwords like "admin1*". I tested this regex in RegexHero as well and it does work.

When I post back my form to the controller the value is also present, yet the model never validates.

Anyone have a clue as to what this could be?

Thanks in advance,

Edit:

I tested with a Regex that validates strings containing only 5 numbers, and that does validate when I input 12345, and fails with other string like "abc". So the regex mechanism seems to work..

Upvotes: 3

Views: 1178

Answers (1)

nemesv
nemesv

Reputation: 139758

Your regex is fine, the problem is with how is the IsValid method implemented in the RegularExpressionAttriubte. Because an input will be valid only if it matches the whole pattern form the start.

An excerpt of the IsValid method as seen by Resharper:

public override bool IsValid(object value)
{
  //...
  Match match = this.Regex.Match(input);
  if (match.Success && match.Index == 0)
    return match.Length == input.Length;
  else
    return false;
}

Your pattern @"(?=.{6,})(?=(.*\d){1,})(?=(.*\W){1,}) matches the input admin1* so match.Success will be true but because of the usage of the Grouping constructs the match.Legth will be always 0 and the match.Length == input.Length evaluates to always false.

It works in the MembershipProvider because it only checks for match.Success, and doesn't care about the length of the match.

I see two possible solution:

  1. Rewrite your regex pattern to not use Grouping constructs (I'm not good at regex so I cannot help here)
  2. Create your own RegularExpressionAttriubte (or derive from the built in one) where in the IsValid method you only check for match.Success

Upvotes: 3

Related Questions