Related Articles

Related Articles

Program to check the validity of a Password
  • Last Updated : 01 Sep, 2020

Password checker program basically checks if the password is valid or not based on password policies mention below:

  • Password should not contain any space.
  • Password should contain at least one digit(0-9).
  • Password length should be between 8 to 15 characters.
  • Password should contain at least one lowercase letter(a-z).
  • Password should contain at least one uppercase letter(A-Z).
  • Password should contain at least one special character ( @, #, %, &, !, $, etc….).

Example:

Input: GeeksForGeeks 
Output: Invalid Password!
This input contains lowercase 
as well as uppercase letters 
but does not contain digits 
and special characters.

Input: Geek$ForGeeks7
Output: Valid Password
This input satisfies all password
policies mentioned above.

Approach:

In this program,

  • we are using String contains () method to check the passwords. This method accepts a CharSequence as an argument and returns true if the argument is present in a string otherwise returns false.
  • Firstly the length of the password has to be checked then whether it contains uppercase, lowercase, digits and special characters.
  • If all of them are present then the method isValid(String password) returns true.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ code to validate a password 
#include<bits/stdc++.h>
using namespace std;
  
// A utility function to check 
// whether a password is valid or not 
bool isValid(string password) 
  
    // For checking if password length 
    // is between 8 and 15 
    if (!((password.length() >= 8) && 
          (password.length() <= 15)))
        return false
  
    // To check space 
    if (password.find(" ") !=
        std::string::npos)
        return false
  
    if (true)
    
        int count = 0; 
  
        // Check digits from 0 to 9 
        for(int i = 0; i <= 9; i++)
        
              
            // To convert int to string 
            string str1 = to_string(i); 
  
            if (password.find(str1) != 
                std::string::npos) 
                count = 1; 
        
        if (count == 0) 
            return false
    
  
    // For special characters 
    if (!((password.find("@") != std::string::npos) ||
          (password.find("#") != std::string::npos) ||
          (password.find("!") != std::string::npos) ||
          (password.find("~") != std::string::npos) ||
          (password.find("$") != std::string::npos) ||
          (password.find("%") != std::string::npos) ||
          (password.find("^") != std::string::npos) ||
          (password.find("&") != std::string::npos) ||
          (password.find("*") != std::string::npos) ||
          (password.find("(") != std::string::npos) ||
          (password.find(")") != std::string::npos) ||
          (password.find("-") != std::string::npos) ||
            (password.find("+") != std::string::npos) ||
          (password.find("/") != std::string::npos) ||
          (password.find(":") != std::string::npos) ||
          (password.find(".") != std::string::npos) ||
          (password.find(",") != std::string::npos) ||
          (password.find("<") != std::string::npos) ||
          (password.find(">") != std::string::npos) ||
          (password.find("?") != std::string::npos) ||
          (password.find("|") != std::string::npos)))
        return false;
      
    if (true)
    
        int count = 0; 
  
        // Checking capital letters 
        for(int i = 65; i <= 90; i++) 
        
              
            // Type casting 
            char c = (char)i;
            string str1(1, c);
              
            if (password.find(str1) !=
                std::string::npos) 
                count = 1; 
        
        if (count == 0) 
            return false
    
  
    if (true)
    
        int count = 0; 
  
        // Checking small letters 
        for(int i = 90; i <= 122; i++)
        
              
            // Type casting 
            char c = (char)i; 
            string str1(1, c); 
  
            if (password.find(str1) != 
                std::string::npos)
                count = 1;
        
        if (count == 0) 
            return false;
    
  
    // If all conditions fails 
    return true
  
// Driver code 
int main() 
    string password1 = "GeeksForGeeks"
      
    if (isValid(password1)) 
        cout << "Valid Password" << endl; 
    else
        cout << "Invalid Password" << endl;
  
    string password2 = "Geek$ForGeeks7";
      
    if (isValid(password2)) 
        cout << "Valid Password" << endl; 
    else
        cout << "Invalid Password" << endl;
  
// This code is contributed by Yash_R

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java code to validate a password
  
public class PasswordValidator {
  
    // A utility function to check
    // whether a password is valid or not
    public static boolean isValid(String password)
    {
  
        // for checking if password length
        // is between 8 and 15
        if (!((password.length() >= 8)
              && (password.length() <= 15))) {
            return false;
        }
  
        // to check space
        if (password.contains(" ")) {
            return false;
        }
        if (true) {
            int count = 0;
  
            // check digits from 0 to 9
            for (int i = 0; i <= 9; i++) {
  
                // to convert int to string
                String str1 = Integer.toString(i);
  
                if (password.contains(str1)) {
                    count = 1;
                }
            }
            if (count == 0) {
                return false;
            }
        }
  
        // for special characters
        if (!(password.contains("@") || password.contains("#")
              || password.contains("!") || password.contains("~")
              || password.contains("$") || password.contains("%")
              || password.contains("^") || password.contains("&")
              || password.contains("*") || password.contains("(")
              || password.contains(")") || password.contains("-")
              || password.contains("+") || password.contains("/")
              || password.contains(":") || password.contains(".")
              || password.contains(", ") || password.contains("<")
              || password.contains(">") || password.contains("?")
              || password.contains("|"))) {
            return false;
        }
  
        if (true) {
            int count = 0;
  
            // checking capital letters
            for (int i = 65; i <= 90; i++) {
  
                // type casting
                char c = (char)i;
  
                String str1 = Character.toString(c);
                if (password.contains(str1)) {
                    count = 1;
                }
            }
            if (count == 0) {
                return false;
            }
        }
  
        if (true) {
            int count = 0;
  
            // checking small letters
            for (int i = 90; i <= 122; i++) {
  
                // type casting
                char c = (char)i;
                String str1 = Character.toString(c);
  
                if (password.contains(str1)) {
                    count = 1;
                }
            }
            if (count == 0) {
                return false;
            }
        }
  
        // if all conditions fails
        return true;
    }
  
    // Driver code
    public static void main(String[] args)
    {
  
        String password1 = "GeeksForGeeks";
  
        if (isValid(password1)) {
            System.out.println("Valid Password");
        }
        else {
            System.out.println("Invalid Password!!!");
        }
  
        String password2 = "Geek$ForGeeks7";
        if (isValid(password2)) {
            System.out.println("Valid Password");
        }
        else {
            System.out.println("Invalid Password!!!");
        }
    }
}

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to validate a password
  
# A utility function to check
# whether a password is valid or not
def isValid(password):
  
    # for checking if password length
    # is between 8 and 15
    if (len(password) < 8 or len(password) > 15):
        return False
  
    # to check space
    if (" " in password):
        return False
  
    if (True):
        count = 0
  
        # check digits from 0 to 9
        arr = ['0', '1', '2', '3'
        '4', '5', '6', '7', '8', '9']
  
        for i in password:
            if i in arr:
                count = 1
                break
  
        if count == 0:
            return False
  
    # for special characters
    if True:
        count = 0
  
        arr = ['@', '#','!','~','$','%','^',
                '&','*','(',',','-','+','/',
                ':','.',',','<','>','?','|']
  
        for i in password:
            if i in arr:
                count = 1
                break
        if count == 0:
            return False
  
    if True:
        count = 0
  
        # checking capital letters
        for i in range(65, 91):
  
            if chr(i) in password:
                count = 1
  
        if (count == 0):
            return False
  
    if (True):
        count = 0
  
        # checking small letters
        for i in range(90, 123):
  
            if chr(i) in password:
                count = 1
  
        if (count == 0):
            return False
  
    # if all conditions fails
    return True
  
# Driver code
password1 = "GeeksForGeeks"
  
if (isValid([i for i in password1])):
    print("Valid Password")
else:
    print("Invalid Password!!!")
  
password2 = "Geek$ForGeeks7"
if (isValid([i for i in password2])):
    print("Valid Password")
else:
    print("Invalid Password!!!")
  
# This code is contributed by mohit kumar 29

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# code to validate a password
using System;
  
class PasswordValidator 
{
  
    // A utility function to check
    // whether a password is valid or not
    public static bool isValid(String password)
    {
  
        // for checking if password length
        // is between 8 and 15
        if (!((password.Length >= 8)
            && (password.Length <= 15)))
        {
            return false;
        }
  
        // to check space
        if (password.Contains(" "))
        {
            return false;
        }
        if (true
        {
            int count = 0;
  
            // check digits from 0 to 9
            for (int i = 0; i <= 9; i++)
            {
  
                // to convert int to string
                String str1 = i.ToString();
  
                if (password.Contains(str1)) 
                {
                    count = 1;
                }
            }
            if (count == 0)
            {
                return false;
            }
        }
  
        // for special characters
        if (!(password.Contains("@") || password.Contains("#")
            || password.Contains("!") || password.Contains("~")
            || password.Contains("$") || password.Contains("%")
            || password.Contains("^") || password.Contains("&")
            || password.Contains("*") || password.Contains("(")
            || password.Contains(")") || password.Contains("-")
            || password.Contains("+") || password.Contains("/")
            || password.Contains(":") || password.Contains(".")
            || password.Contains(", ") || password.Contains("<")
            || password.Contains(">") || password.Contains("?")
            || password.Contains("|"))) 
        {
            return false;
        }
  
        if (true)
        {
            int count = 0;
  
            // checking capital letters
            for (int i = 65; i <= 90; i++)
            {
  
                // type casting
                char c = (char)i;
  
                String str1 = c.ToString();
                if (password.Contains(str1))
                {
                    count = 1;
                }
            }
            if (count == 0)
            {
                return false;
            }
        }
  
        if (true)
        {
            int count = 0;
  
            // checking small letters
            for (int i = 90; i <= 122; i++) 
            {
  
                // type casting
                char c = (char)i;
                String str1 = c.ToString();
  
                if (password.Contains(str1)) 
                {
                    count = 1;
                }
            }
            if (count == 0)
            {
                return false;
            }
        }
  
        // if all conditions fails
        return true;
    }
  
    // Driver code
    public static void Main(String[] args)
    {
  
        String password1 = "GeeksForGeeks";
  
        if (isValid(password1))
        {
            Console.WriteLine("Valid Password");
        }
        else 
        {
            Console.WriteLine("Invalid Password!!!");
        }
  
        String password2 = "Geek$ForGeeks7";
        if (isValid(password2)) 
        {
            Console.WriteLine("Valid Password");
        }
        else 
        {
            Console.WriteLine("Invalid Password!!!");
        }
    }
}
  
// This code is contributed by Rajput-Ji

chevron_right


Output:

Invalid Password!!!
Valid Password

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up
Recommended Articles
Page :