Manish
Manish

Reputation: 1776

Unable to check password length using regex in MVC4

I am experimenting with the use of regex to check password complexity with MVC4 data annotations. I started with a simple regex to check for length, but the following does not work with strings of any length. What error am I making?

[RegularExpression(@"^(?=.{8,})$", ErrorMessage = "Password not strong enough")]
[Required]
[DataType(DataType.Password)]
public string Password { get; set; }

Upvotes: 1

Views: 798

Answers (2)

acarlon
acarlon

Reputation: 17264

As far as the simple regex you were trying goes, you can just use:

^.{8,}$

You don't want the forward lookup (?=). See my description of why this is the case at the end.

For simple string length checking, you can just use the StringLength length attribute if you are using asp.net 4.0:

[StringLength(8, MinimumLength=1)]

(Note: as Tommy pointed out in the comments, you would want a regex for the full password checking). If you are looking for more complex password regexes, then I suggest you look at tommy's answer and here and here to begin.

Why (?=) doesn't work

  • ^ - match the start of the string.
  • .{8,} - Then look forward and see if there are at least 8 characters. (remember forward lookup doesn't change the test position so this will still be the start of the string).
  • Have we reached the end ($)? No -> Fail.

Another example is that .+(?=.{8,})$ will fail because there is no such position in the string that is followed by 8 characters and the next character from the test position is the end of string $.

A final example is ^.(?=.{7,}) which will match the first character of an (at least) 8 character string. This is because only the first character is preceeded by the beginning ^

Upvotes: 2

Tommy
Tommy

Reputation: 39807

Given that you want to verify length as well as some other password complexity rules based on your opening sentence, I recommend that you check out some of the Regex blogs concerning "Password Complexity Regex" on the internet. For example, if you wanted to ensure that a password was at least 8-20 characters long and contained one upper and one lower case letter as well as a number, you would use the following regex

((?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,20})

Which basically breaks down to, I need at least 8 (no more than 20) characters, at least one must be a number, at least one must be a-z and at least one must be A-Z. There are other examples and bits that you can put together.

For testing your regex, I would recommend a regex testing site such as http://regexhero.net/tester/. In conjunction with the MSDN, you should be able to make some pretty nifty expressions.

Upvotes: 2

Related Questions