[Solved] Password Validator - PHP Function Task

  

5
Topic starter

Write a program that checks if a given password is valid.

Password rules are:

  • 6 – 10 characters (inclusive)
  • Consists only of letters and digits
  • Have at least 2 digits

If a password is valid print “Password is valid”. If it is not valid, for every unfulfilled rule print a message:

  • "Password must be between 6 and 10 characters"
  • "Password must consist only of letters and digits"
  • "Password must have at least 2 digits"

Examples:

password validator php function task

Hint: Write a function for each rule.

2 Answers
4

Here is my code with functions:

<?php
 
$password = readline();
$validLength = hasValidLength($password);
$validContent = hasValidContent($password);
$validEnoughDigits = hasEnoughDigits($password);
 
if (!$validLength) {
    echo "Password must be between 6 and 10 characters" . PHP_EOL;
}
 
if (!$validContent) {
    echo "Password must consist only of letters and digits" . PHP_EOL;
}
 
if (!$validEnoughDigits) {
    echo "Password must have at least 2 digits" . PHP_EOL;
}
 
if (hasValidLength($password) && hasValidContent($password) && hasEnoughDigits($password)) {
    echo "Password is valid" . PHP_EOL;
}
 
//function checking password's length
function hasValidLength(string $pass): bool {
    if (strlen($pass) < 6 || strlen($pass) > 10) {
        return false;
    }
    return true;
}
 
//function checking if the password has only digits and numbers
function hasValidContent(string $pass): bool {
    if (!ctype_alnum($pass)) {
        return false;
    }
    return true;
}
 
//function checking if the password has at least 2 numbers
function hasEnoughDigits(string $pass): bool {
    $numberCheck = "";
    for ($i = 0; $i < strlen($pass); $i++) {
        if (ctype_digit($pass[$i])) {
            $numberCheck .= $pass[$i];
        }
    }
 
    if (strlen($numberCheck) < 2) {
        return false;
    }
    return true;
}
2

My solution without functions - only with logic:

<?php
 
$password = readline();
$valid = true;
 
//Checking password's length
if (strlen($password) < 6 || strlen($password) > 10) {
    echo "Password must be between 6 and 10 characters" . PHP_EOL;
    $valid = false;
}
 
//Checking if the password has only digits and numbers
if (!ctype_alnum($password)) {
    echo "Password must consist only of letters and digits" . PHP_EOL;
    $valid = false;
}
 
//Checking if the password has at least 2 numbers
$numberCheck = "";
for ($i = 0; $i < strlen($password); $i++) {
    if (ctype_digit($password[$i])) {
        $numberCheck .= $password[$i];
    }
}
 
if (strlen($numberCheck) < 2) {
    echo "Password must have at least 2 digits" . PHP_EOL;
    $valid = false;
}
 
if ($valid == true) {
    echo "Password is valid" . PHP_EOL;
}

I've used: ctype_alnum() and ctype_digit() PHP functions for validation of the password

Share: