Programa para verificar la validez de la contraseña sin usar expresiones regulares.

El programa de verificación de contraseñas básicamente verifica si una contraseña es válida o no según las políticas de contraseñas que se mencionan a continuación: 
 

  • La contraseña no debe contener ningún espacio. 
     
  • La contraseña debe contener al menos un dígito (0-9). 
     
  • La longitud de la contraseña debe tener entre 8 y 15 caracteres. 
     
  • La contraseña debe contener al menos una letra minúscula (az). 
     
  • La contraseña debe contener al menos una letra mayúscula (AZ). 
     
  • La contraseña debe contener al menos un carácter especial ( @, #, %, &, !, $, etc.).

Ejemplo: 
 

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.

Enfoque:
En este programa, 
 

  • estamos usando el método String contains() para verificar las contraseñas. Este método acepta CharSequence como argumento y devuelve verdadero si el argumento está presente en una string; de lo contrario, devuelve falso. 
     
  • En primer lugar, se debe verificar la longitud de la contraseña y luego si contiene mayúsculas, minúsculas, dígitos y caracteres especiales. 
     
  • Si todos están presentes, el método isValid (String password) devuelve verdadero.

A continuación se muestra la implementación del enfoque anterior: 
 

Java

// 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 = 97; 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(password1 + " - Valid Password");
        }
        else {
            System.out.println(password1 + " - Invalid Password!");
        }
 
        String password2 = "Geek$ForGeeks7";
        if (isValid(password2)) {
            System.out.println(password2 + " - Valid Password");
        }
        else {
            System.out.println(password2 + " - Invalid Password!");
        }
    }
}

C++

// 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 = 97; 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

Python3

# 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(97, 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

C#

// 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 = 97; 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
Producción

GeeksForGeeks - Invalid Password!
Geek$ForGeeks7 - Valid Password

Publicación traducida automáticamente

Artículo escrito por Anoop_Varghese y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *