Start learning free

LESSON 196 OF 289 · PROJECTS: EVERYDAY PROGRAMS

Password Strength V2 in TypeScript: Length and a Digit Flag

Practice Read the full explanation

Extend the length check with a second rule: the password must also contain at least one digit.

You start with:

const password: string = "Secret99";

Build:

Length: 8
Has digit: True
Strong

Rules:

  • Print "Length: " followed by the number of characters.
  • Loop through each character to set a boolean flag hasDigit, which starts as false and becomes true when a digit is seen.
  • Print "Has digit: " followed by the flag. Write it as True or False with a capital letter, exactly as in the example (your language's own boolean prints differently, so choose the text yourself).
  • If the length is at least 8 and hasDigit is true, print Strong; otherwise print Weak.

Try other passwords: with abcdefgh the output is

Length: 8
Has digit: False
Weak

Use a regex test like /[0-9]/.test(c) in the loop. JavaScript prints true/false by default; convert with a ternary (hasDigit ? "True" : "False").

const password: string = "Secret99";

const length: number = password.length;
console.log("Length: " + length);
let hasDigit: boolean = false;
for (const c of password) {
    if (/[0-9]/.test(c)) {
        hasDigit = true;
    }
}
console.log("Has digit: " + (hasDigit ? "True" : "False"));
if (length >= 8 && hasDigit) {
    console.log("Strong");
} else {
    console.log("Weak");
}

STEP 1 OF 8
    Ctrl + Enter to check

    TYPESCRIPT · PROJECTS: EVERYDAY PROGRAMS

    Password Strength V2 in TypeScript, explained

    Problem overview

    The checker now has two rules. A password is Strong only if it has at least 8 characters and contains at least one digit; otherwise it is Weak. The program also prints the facts it used. For Secret99 the output is:

    Length: 8
    Has digit: True
    Strong

    For abcdefgh the length is 8 but there is no digit, so the output is Length: 8, Has digit: False and Weak. Note the capital letters in True and False: they are text the program chooses, not what TypeScript prints for a boolean.

    Approach: a flag that flips once

    The length is one call away, but "contains a digit" needs a look at every character. The standard pattern is a boolean flag. It starts as false, meaning "no digit seen yet", and a loop over the characters sets it to true the moment one digit appears. Nothing in the loop ever sets it back, so after the loop the flag answers the question for the whole string.

    A flag is the better tool here than a counter or an early return because the program does not need to know where the digit is or how many there are. Once the flag is true, the answer can't change.

    The check for a single character is a regular expression, /[0-9]/.test(c). The part between the slashes is a pattern, and [0-9] matches one character in the range 0 to 9. The method .test returns true or false.

    Following the loop on Secret99: for the first six characters, S, e, c, r, e and t, the test is false and hasDigit stays false. At index 6 the character is 9, the test is true and the flag flips. The last character, another 9, sets it to true again, which changes nothing. The loop could stop at the first digit, but it doesn't need to: with passwords this short, finishing the pass is simpler and just as correct.

    Step by step

    1. Store length as a const number, since it is used for the printed line and for the rule.
    2. Print the first line, "Length: " and the number.
    3. Create hasDigit with let, typed boolean, starting at false. It is let because it changes.
    4. Loop over the characters with for (const c of password). A string is iterable, and for...of gives one character per pass.
    5. Test each character. Inside the loop, if /[0-9]/.test(c) is true, set hasDigit to true.
    6. Print the flag as text after the loop. A ternary picks the word: hasDigit ? "True" : "False". It sits in parentheses so that + joins the finished word to the label.
    7. Write the verdict. The condition length >= 8 && hasDigit is true only when both parts are true, and that case prints Strong.
    8. Add the else, which prints Weak for everything else: too short, no digit, or both.

    The solution in TypeScript

    const password: string = "Secret99";
    
    const length: number = password.length;
    console.log("Length: " + length);
    let hasDigit: boolean = false;
    for (const c of password) {
        if (/[0-9]/.test(c)) {
            hasDigit = true;
        }
    }
    console.log("Has digit: " + (hasDigit ? "True" : "False"));
    if (length >= 8 && hasDigit) {
        console.log("Strong");
    } else {
        console.log("Weak");
    }

    Details that matter:

    • Printing a boolean directly gives lowercase. "Has digit: " + hasDigit would print Has digit: true. The required text is True, so the ternary supplies it.
    • The parentheses around the ternary matter. Without them, + binds tighter than ?:, so the label and the flag are joined first, and the ternary would test that whole non-empty string, which is always truthy. With hasDigit false, the line console.log("Has digit: " + hasDigit ? "True" : "False") prints just True.
    • && stops early. If length >= 8 is false, the second operand isn't evaluated. Here that is harmless, because hasDigit is already computed.
    • [0-9] matches only the ASCII digits. The pattern returns false for the Arabic-Indic digit three, for example, so only 0 to 9 count.

    Complexity

    The loop visits each of the n characters once and does a constant amount of work for each, so the time is O(n). The program stores a few variables whatever the password's size, so the extra space is O(1). The regular expression is a literal, and each call tests a single character, so it adds no hidden cost per pass.

    Edge cases and common mistakes

    • Declaring hasDigit with const. The assignment inside the loop would be an error. Use let.
    • Setting the flag to false in an else inside the loop. Then a digit followed by a letter would erase the result. The flag only ever moves from false to true.
    • Printing the flag inside the loop. The line must appear once, after the loop has seen every character.
    • Using || instead of &&. A password with 8 letters and no digit would be reported as Strong.
    • Short passwords with a digit. abc12 has a digit but only 5 characters, so the output is Length: 5, Has digit: True and Weak. Likewise 12345678 passes both rules and is Strong: the checker only tests the two rules.

    Testing

    Change password in the editor above:

    passwordLengthHas digitVerdict
    Secret998TrueStrong
    abcdefgh8FalseWeak
    abc125TrueWeak
    123456788TrueStrong
    Keep going with TypeScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free