In this article, we will write a C# program to check password.
While creating a password, you may have seen the validation requirements on a website like a password should be strong and have −
- Min 8 char and max 14 char
- One lower case
- No white space
- One upper case
- One special char
Let us see how to check the conditions one by one −
Min 8 char and max 14 char
1 2 3 4 | if (passwd.Length < 8 || passwd.Length > 14) return false; |
Atleast one lower case
1 2 3 4 | if (!passwd.Any(char.IsLower)) return false; |
No white space
1 2 3 4 | if (passwd.Contains(" ")) return false; |
One upper case
1 2 3 4 | if (!passwd.Any(char.IsUpper)) return false; |
Check for one special character
1 2 3 4 5 6 7 8 | string specialCh = @"%!@#$%^&*()?/>.<,:;'\|}]{[_~`+=-" + "\""; char[] specialCh = specialCh.ToCharArray(); foreach (char ch in specialChArray) { if (passwd.Contains(ch)) return true; } |
Example 2:
The password should have:
1. min 6 char and max 12 char
2. No two similar chars consecutively
3. 1 lower case
4. 1 upper case
5. 1 special char
6. No white space
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 | using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CodingPuzzles { //Write password checker method - must contain min 6 char and max 12 char, //No two similar chars consecutively, 1 lower case, 1 upper case, 1 special char, no white space public static class PasswordChecker { public static bool CheckPassword(string pass) { //min 6 chars, max 12 chars if (pass.Length < 6 || pass.Length > 12) return false; //No white space if (pass.Contains(" ")) return false; //At least 1 upper case letter if (!pass.Any(char.IsUpper)) return false; //At least 1 lower case letter if (!pass.Any(char.IsLower)) return false; //No two similar chars consecutively for (int i = 0; i < pass.Length - 1; i++) { if (pass[i] == pass[i + 1]) return false; } //At least 1 special char string specialCharacters = @"%!@#$%^&*()?/>.<,:;'\|}]{[_~`+=-" + "\""; char[] specialCharactersArray = specialCharacters.ToCharArray(); foreach (char c in specialCharactersArray) { if (pass.Contains(c)) return true; } return false; } } } |