Golang : Check if password length meet the requirement
Problem :
You need to check the password's length entered by users. How to do that in Golang?
Solution :
Use the builtin len()
function to evaluate the length of the password and return true if the password length is acceptable or false if not.
See example :
package main
import "fmt"
func checkLength(value string, min, max int) bool {
pwdLen := len(value)
if min > 0 && pwdLen < min {
return false
}
if max > 0 && pwdLen > max {
return false
}
return true
}
func main() {
password := "abc12"
passwordMin := 6
passwordMax := 20
if !checkLength(password, passwordMin, passwordMax) {
fmt.Println("Password needs to be more than 6 characters and less than 20 characters")
} else {
fmt.Println("Password length accepted")
}
password = "abc1234"
if !checkLength(password, passwordMin, passwordMax) {
fmt.Println("Password needs to be more than 6 characters and less than 20 characters")
} else {
fmt.Println("Password length accepted")
}
}
Sample output :
Password needs to be more than 6 characters and less than 20 characters
Password length accepted
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+14.5k Golang : Send email with attachment(RFC2822) using Gmail API example
+20.1k Golang : How to get own program name during runtime ?
+4.9k Python : Convert(cast) bytes to string example
+44.7k Golang : Use wildcard patterns with filepath.Glob() example
+26.7k Golang : Convert file content into array of bytes
+29.7k Golang : Get and Set User-Agent examples
+8k Golang : Check from web if Go application is running or not
+5.9k Golang : Generate multiplication table from an integer example
+7.3k Golang : Calculate how many weeks left to go in a given year
+5.5k Unix/Linux : How to find out the hard disk size?
+8.2k Golang : Oanda bot with Telegram and RSI example
+14.4k Golang : Rename directory