Skip to content

Instantly share code, notes, and snippets.

@makafanpeter
Created July 18, 2024 17:36
Show Gist options
  • Save makafanpeter/e83b0ebe3b293d8e55fbc5ec00119fa6 to your computer and use it in GitHub Desktop.
Save makafanpeter/e83b0ebe3b293d8e55fbc5ec00119fa6 to your computer and use it in GitHub Desktop.
using System.Text.RegularExpressions;
var pRequirement = new PasswordRequirement(8, true, true, true, true);
var results = ValidatePasswordRequirement(testPassword,pRequirement);
Console.WriteLine(!results.Item1 ? results.Item2 : "Password is valid");
(bool, string) ValidatePasswordRequirement(string password, PasswordRequirement passwordRequirement)
{
//1. checks the value
if (string.IsNullOrEmpty(password))
{
return (false, "The password cannot be empty");
}
//2. Validate minimum length
if (password.Length < passwordRequirement.MinimumLength)
{
return (false ,$"The password must be over {passwordRequirement.MinimumLength} characters.");
}
//3. At least one lowercase character
if (passwordRequirement.RequireLowercase)
{
Match lowercase = Regex.Match(password, @"^(?=.*[a-z])");
if (!lowercase.Success)
{
return (false ,"The password must contain at least one lowercase character.");
}
}
//4. At least one upper case character
if (passwordRequirement.RequireUppercase)
{
Match uppercase = Regex.Match(password, @"^(?=.*[A-Z])");
if (!uppercase.Success)
{
return (false ,"The password must contain at least one uppercase character.");
}
}
// 3. At least one digit
if (passwordRequirement.RequireDigit)
{
Match digit = Regex.Match(password, @"^(?=.*\d)");
if (!digit.Success)
{
return (false ,"The password must contain at least one digit.");
}
}
// 4. At least one special character
if (passwordRequirement.RequireNonAlphanumeric)
{
Match specialCharacter = Regex.Match(password, @"^(?=.*[^\da-zA-Z])");
if (!specialCharacter.Success)
{
return (false ,"The password must contain at least one non-alphanumeric character.");
}
}
return (true, "Password is valid");
}
}
public record PasswordRequirement(
int MinimumLength,
bool RequireUppercase,
bool RequireLowercase,
bool RequireNonAlphanumeric,
bool RequireDigit
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment