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
+7.2k Golang : File system scanning
+6.6k Golang : Derive cryptographic key from passwords with Argon2
+13.1k Golang : Convert(cast) int to int64
+8.2k Golang : Check if integer is power of four example
+10.4k Golang : Generate 403 Forbidden to protect a page or prevent indexing by search engine
+6.7k Golang : Experimental emojis or emoticons icons programming language
+20.1k Golang : Compare floating-point numbers
+4.8k Javascript : How to get width and height of a div?
+5.3k Golang : Reclaim memory occupied by make() example
+7.6k Golang : Convert(cast) io.Reader type to string
+14.3k Golang : How to shuffle elements in array or slice?
+7.5k Golang : Shuffle strings array