Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
511 views
in Technique[技术] by (71.8m points)

asp.net mvc - Password validation (regex?)

I need to write some validation rules for a user password with the following requirements. C# ASP.NET MVC.

Passwords must be 6 - 8 characters
Must include at least one character each from at least three of the following categories:

  1. Upper-case letters
  2. Lower-case letters
  3. Numeric digits
  4. Non-alpha-numeric characters (e.g.,!@#$%...)

Must not contain any sequence of 3 or more characters in common with the username
Must not repeat any of the previous 1 passwords
Must be changed if the password is believed to be compromised in any way

Currently i've written a bunch of really messy validation rules using if statements and loops (especially the 3 characters in sequence with username part), which is currently functional but it just feels like its wrong. Is there a better approach I can take?

Thankyou

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I wrote one very similar to what you are describing. They can be done as a regular expression, and when complete (at least for myself) it was a very rewarding accomplishment.

To accomplish this you are going to need to use a regex feature called lookaheads. See the information on the regular-expression.info site for all the gory details.

The second thing you will need is a real time regular expression tester to help you prototype your regex. I suggestion you check out Rubular. Create several passwords that should work, and some that shouldn't work and start from there as your starting point.

Edit: To elaborate on my above comment. Not every one of your requirements can or should be solved via a regex. Namely, the requirements you listed as:

  • Must not contain any sequence of 3 or more characters in common with the username
  • Must not repeat any of the previous 1 passwords
  • Must be changed if the password is believed to be compromised in any way

Should probably be handled separately from the main password validation regex, as these are highly contextual. The "sequence of 3 or more characters in common with the username" can probably be handled on the client side. However, the other two items are probably best left handled on the server side.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...