How to validate a password (must contain uppercase, lowercase, digit, and special character) in C

1 Answer

0 votes
#include <stdio.h>
#include <string.h> // strchr
#include <ctype.h>
#include <stdbool.h>

// One function that checks if the password is valid
bool isValidPassword(const char *pass) {
    bool upper = false, lower = false, digit = false, special = false;
    const char *specials = "!@#$%^&*";

    for (int i = 0; pass[i] != '\0'; i++) {
        char ch = pass[i];

        if (isupper(ch)) upper = true;
        else if (islower(ch)) lower = true;
        else if (isdigit(ch)) digit = true;
        else if (strchr(specials, ch) != NULL) special = true;
    }

    return upper && lower && digit && special;
}

int main() {
    char password1[] = "aT5#op09!";
    if (isValidPassword(password1))
        printf("Valid password\n");
    else
        printf("Invalid password\n");

    char password2[] = "aT#opQ!";
    if (isValidPassword(password2))
        printf("Valid password\n");
    else
        printf("Invalid password\n");

    return 0;
}


/*
run:

Valid password
Invalid password

*/

 



answered Apr 25 by avibootz
edited Apr 25 by avibootz
...