开发者

Password validation (regex?)

开发者 https://www.devze.com 2023-01-24 08:05 出处:网络
I need to write some validation rules for a user password with the following requirements. C# ASP.NET MVC.

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 开发者_如何学Goprevious 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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消