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
+2.1k Golang : How to find out similarity between two strings with Jaro-Winkler Distance?
+12k Golang : Convert uint value to string type
+2.1k Golang : ROT32768 (rotate by 0x80) UTF-8 strings example
+7.2k Golang : Fix cannot use buffer (type bytes.Buffer) as type io.Writer(Write method has pointer receiver) error
+2.7k Golang : How to get capacity of a slice or array?
+2.9k Linux/Unix : Commands that you need to be careful about
+11.3k Golang : Print leading(padding) zero or spaces in fmt.Printf?
+2.5k Clean up Visual Studio For Mac installation failed disk full problem
+5.5k Golang : Convert file unix timestamp to UTC time example
+4.6k Swift : Convert (cast) Character to Integer?
+3.7k Python : Fix SyntaxError: Non-ASCII character in file, but no encoding declared
+3.2k Golang : Use modern ciphers only in secure connection