C++ program for password validation

In this blog, We will see, How to validate password in C++ programming language.

What is Password Validation?

When we create a password on any site then it must contain a combination of upper case, and lower case letters along with mathematical digits with some special characters too.

If any criteria will be unable to match then it will show the strength of the password as weak, moderate, and strong.

This whole criteria comes under password validation.

C++ program for the password validation

#include <bits/stdc++.h> 
using namespace std; 
  
void checkpassword(string& password) 
{ 
    int n = password.length();      
    bool hasLower = false, hasUpper = false, hasDigit = false; 
  
    for (int i = 0; i < n; i++) { 
        if (islower(password[i])) 
            hasLower = true; 
        if (isupper(password[i])) 
            hasUpper = true; 
        if (isdigit(password[i])) 
            hasDigit = true; 
    } 
  
    // Displaying the strength of password 
    
    cout << "Strength of password you have entered is :-"; 
    
    if ( hasUpper && hasDigit && hasLower && (n >= 6)) // considering a strong must be of length 6 or more
        cout << "Strong" << endl; 
    else if ((hasLower || hasUpper) && hasDigit && (n >=6)) 
        //when at least a lower case or uppercase is used along with digit
        cout << "Moderate" << endl; 
    else
        cout << "Weak" << endl; 
} 
  
 
int main() 
{   cout << "Welcome, lets check your password " << endl;
    cout << "Considering average length of a strong password should be more then 6 character " << endl;
  cout << "Please enter a password which should contain :- " << endl;
  cout << " * at least one upper and lowercase letter " << endl;
  cout << " * and also at least one digit " << endl;
    string password;
    cout <<"Enter password"<<endl;
  getline(cin,password);
    checkpassword(password); 
    return 0; 
}

Output of the above code

For strong password

For moderate password

For weak password

Explanation of the code

  • The user enters a password to be checked.
  • The password provided by the user will now be checked for uppercase, lowercase letters and numbers.
  • Password strength is divided into 3 categories, which are strong, medium and weak.
  • If a password contains all of them, it is considered a strong password.
  • If the password contains at least one uppercase or lowercase letter and at least 6 other digits, then it is considered medium.
  • otherwise, it’s a weak password.