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
+13.8k Golang : Activate web camera and broadcast out base64 encoded images
+41.4k Golang : How to count duplicate items in slice/array?
+7.5k Linux : How to fix Brother HL-1110 printing blank page problem
+14.2k Golang : Fix cannot use buffer (type bytes.Buffer) as type io.Writer(Write method has pointer receiver) error
+7.2k Golang : Get environment variable
+21k Golang : Underscore or snake_case to camel case example
+6.7k Golang : Convert an executable file into []byte example
+8.3k How to show different content from website server when AdBlock is detected?
+7.8k Gogland : Where to put source code files in package directory for rookie
+7.1k Golang : Fibonacci number generator examples
+8.7k Golang : Convert(cast) []byte to io.Reader type
+24.2k Golang : Upload to S3 with official aws-sdk-go package