Check Password Validity in C#



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

if (passwd.Length < 8 || passwd.Length > 14)
return false;

Atleast one lower case

if (!passwd.Any(char.IsLower))
return false;

No white space

if (passwd.Contains(" "))
return false;

One upper case

if (!passwd.Any(char.IsUpper))
return false;

Check for one special character

string specialCh = @"%!@#$%^&*()?/>.<,:;'\|}]{[_~`+=-" + "\"";
char[] specialCh = specialCh.ToCharArray();
foreach (char ch in specialChArray) {
   if (passwd.Contains(ch))
      return true;
}
Samual Sam
Samual Sam

Updated on: 2020-06-19T09:05:00+05:30

871 Views

Kickstart Your Career

Get certified by completing the course

Get Started