Mit dieser Methode kann überprüft werden, ob ein Passwort den gegeben Sicherheitsrichtlinien entspricht.
Benötigtes Using:
using System.Text.RegularExpressions;
/// <summary>
/// Validates the password.
/// </summary>
/// <param name="passwordToValidate">The password to validate.</param>
/// <param name="minimumPasswordLength">Minimum length of the password.</param>
/// <param name="minimumNumberOfSpecialCharaters">The minimum number of special charaters.</param>
/// <param name="minimumNumberOfUpperCaseCharaters">The minimum number of upper case charaters.</param>
/// <param name="minimumNumberOfLowerCaseCharaters">The minimum number of lower case charaters.</param>
/// <param name="minimumNumberOfNumericCharaters">The minimum number of numeric charaters.</param>
/// <returns></returns>
public bool ValidatePassword(string passwordToValidate, int minimumPasswordLength, int minimumNumberOfSpecialCharaters, int minimumNumberOfUpperCaseCharaters, int minimumNumberOfLowerCaseCharaters, int minimumNumberOfNumericCharaters)
{
if (passwordToValidate == null || passwordToValidate.Length < minimumPasswordLength)
return false;
int numberOfSpecialCharaters = 0;
int numberOfLowerCaseCharaters = 0;
int numberOfUpperCaseCharaters = 0;
int numberOfNumericCharaters = 0;
var regexSpecialCharater = new Regex("[^A-Za-z0-9]");
var regexLowerCaseCharater = new Regex("[a-z]");
var regexUpperCaseCharater = new Regex("[A-Z]");
var regexNumericCharaters = new Regex("[0-9]");
for (int i = 0; i < passwordToValidate.Length; i++)
{
if (regexSpecialCharater.IsMatch(passwordToValidate[i].ToString()))
numberOfSpecialCharaters++;
if (regexLowerCaseCharater.IsMatch(passwordToValidate[i].ToString()))
numberOfLowerCaseCharaters++;
if (regexUpperCaseCharater.IsMatch(passwordToValidate[i].ToString()))
numberOfUpperCaseCharaters++;
if (regexNumericCharaters.IsMatch(passwordToValidate[i].ToString()))
numberOfNumericCharaters++;
}
return (numberOfSpecialCharaters >= minimumNumberOfSpecialCharaters)
&& (numberOfLowerCaseCharaters >= minimumNumberOfLowerCaseCharaters)
&& (numberOfUpperCaseCharaters >= minimumNumberOfUpperCaseCharaters)
&& (numberOfNumericCharaters >= minimumNumberOfNumericCharaters);
}
3 Kommentare zum Snippet