Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I can't take the credit, as I stole this from <a href="http://social.msdn.microsoft.com/Forums/is/csharpgeneral/thread/5e3f27d2-49af-410a-85a2-3c47e3f77fb1">here</a></p> <pre><code>using System.Text; using System.Text.RegularExpressions; public enum PasswordScore { Blank = 0, VeryWeak = 1, Weak = 2, Medium = 3, Strong = 4, VeryStrong = 5 } public class PasswordAdvisor { public static PasswordScore CheckStrength(string password) { int score = 0; if (password.Length &lt; 1) return PasswordScore.Blank; if (password.Length &lt; 4) return PasswordScore.VeryWeak; if (password.Length &gt;= 8) score++; if (password.Length &gt;= 12) score++; if (Regex.Match(password, @"/\d+/", RegexOptions.ECMAScript).Success) score++; if (Regex.Match(password, @"/[a-z]/", RegexOptions.ECMAScript).Success &amp;&amp; Regex.Match(password, @"/[A-Z]/", RegexOptions.ECMAScript).Success) score++; if (Regex.Match(password, @"/.[!,@,#,$,%,^,&amp;,*,?,_,~,-,£,(,)]/", RegexOptions.ECMAScript).Success) score++; return (PasswordScore)score; } } </code></pre> <p>Note the use of regex for checking for upper case characters. This appears to be a decent approach, as it checks length, use of upper and lower case characters, numeric digits and special characters.</p> <p>** Update **</p> <p>I know the question is now closed, but I can add more explanation for VoidKing to understand some of the concepts.</p> <p>A PasswordScore is returned from the CheckStrength method, which can be used as the condition for what to do next in your code.</p> <p>Here's an untested demo of how the above code could be used:</p> <pre><code>String password = "MyDummy_Password"; // Substitute with the user input string PasswordScore passwordStrengthScore = PasswordAdvisor.CheckStrength(password); switch (passwordStrengthScore) { case PasswordScore.Blank: case PasswordScore.VeryWeak: case PasswordScore.Weak: // Show an error message to the user break; case PasswordScore.Medium: case PasswordScore.Strong: case PasswordScore.VeryStrong: // Password deemed strong enough, allow user to be added to database etc break; } </code></pre> <p>Enums are used in this case as a means of classifying the strength of the password into human-readable groups. Keeps the code clean, and makes it obvious what is going on in the code.</p> <p>Regarding the use of Regex's, if you're unfamiliar with the concept of them and how and when to use them, I suggest doing some research as these can be useful in many different scenarios for checking for patterns in strings. Perhaps start <a href="http://www.regular-expressions.info/">here</a>.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload