10. Password Strength

As part of improving security, Textio wants to enforce a new password policy. A valid password must meet the following criteria:

  • At least 5 characters long but no more than 12 characters.

  • Contains at least one uppercase letter.

  • Contains at least one digit.

A string is really just a read-only slice of bytesarrow-up-right. This means that you can use the same techniques you learned in the previous lesson to iterate over the characters of a string.

Assignment

Implement the isValidPassword function by looping through each character in the password string. Make sure the password is long enough and includes at least one uppercase letter and one digit.

Assume passwords consist of ASCII charactersarrow-up-right only.

Tip

circle-info

Remember that characters in Go stringsarrow-up-right are really just bytes under the hood. You can compare a character to another character like 'A' or '0' to check if it falls within a certain range.

Solution

original_solution.go
package main
import "unicode"

func isValidPassword(password string) bool {
	isStrong:= false
	if 4<len(password)&& len(password)<=12{
		for _, char:= range password{
			if unicode.IsUpper(char){
				for _, char2:= range password{
					if unicode.IsDigit(char2){
						isStrong = true
					}
				}
			}
		}
	
	}
	return isStrong
}

There are two things I’d improve:

1

Avoid the nested double loop

Right now, for every uppercase character you find, you loop over the whole password again to look for a digit. That’s correct but inefficient.

2

Track flags in a single loop

A cleaner approach is to track flags in a single loop: