This should meet all your requirements. It does not use regex.
private bool TestPassword(string passwordText, int minimumLength=5, int maximumLength=12,int minimumNumbers=1, int minimumSpecialCharacters=1) { //Assumes that special characters are anything except upper and lower case letters and digits //Assumes that ASCII is being used (not suitable for many languages) int letters = 0; int digits = 0; int specialCharacters = 0; //Make sure there are enough total characters if (passwordText.Length < minimumLength) { ShowError("You must have at least " + minimumLength + " characters in your password."); return false; } //Make sure there are enough total characters if (passwordText.Length > maximumLength) { ShowError("You must have no more than " + maximumLength + " characters in your password."); return false; } foreach (var ch in passwordText) { if (char.IsLetter(ch)) letters++; //increment letters if (char.IsDigit(ch)) digits++; //increment digits //Test for only letters and numbers... if (!((ch > 47 && ch < 58) || (ch > 64 && ch < 91) || (ch > 96 && ch < 123))) { specialCharacters++; } } //Make sure there are enough digits if (digits < minimumNumbers) { ShowError("You must have at least " + minimumNumbers + " numbers in your password."); return false; } //Make sure there are enough special characters -- !(a-zA-Z0-9) if (specialCharacters < minimumSpecialCharacters) { ShowError("You must have at least " + minimumSpecialCharacters + " special characters (like @,$,%,#) in your password."); return false; } return true; } private void ShowError(string errorMessage) { Console.WriteLine(errorMessage); }
This is an example of what to call it:
private void txtPassword_TextChanged(object sender, EventArgs e) { bool temp = TestPassword(txtPassword.Text, 6, 10, 2, 1); }
This does not check for a mixture of upper and lower case letters, which may be preferable. To do this, simply fold the char condition up, where (ch > 96 && ch < 123) is a set of lowercase letters, and (ch > 64 && ch < 91) is uppercase.
Regex is shorter and simpler (for those who are good with it), and there are many examples on the Internet, but this method is better for setting feedback for the user.
Victor stoddard
source share