Drill

ProblemsJavaScript › validation

Score a password

mediumvalidationJavaScript

The sign-up form shows a strength meter with five segments, one for each rule the password satisfies.

passwordScore(password: string) → int

Solve it in the editor →

Where you start

function passwordScore(password) {
  
}

Worked examples

CallResult
passwordScore("abc")1
passwordScore("abcdefgh")2
passwordScore("Abcdefg1")4
passwordScore("Abcdefg1!")5

Hint

Five independent booleans, added up. No early returns.

Reference solution in JavaScript
function passwordScore(password) {
  let lower = false, upper = false, digit = false, other = false;
  for (const c of password) {
    if (c >= 'a' && c <= 'z') lower = true;
    else if (c >= 'A' && c <= 'Z') upper = true;
    else if (c >= '0' && c <= '9') digit = true;
    else other = true;
  }
  return (password.length >= 8 ? 1 : 0) + (lower ? 1 : 0) + (upper ? 1 : 0) + (digit ? 1 : 0) + (other ? 1 : 0);
}

The same problem in another language

More validation problems in JavaScript