Last active
April 17, 2023 00:08
-
-
Save cjaewon/dece2b4b7b4adc14a0d4b561276157c0 to your computer and use it in GitHub Desktop.
golang echo validator (password)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package main | |
| import ( | |
| "v/utils" | |
| "os" | |
| "github.com/go-playground/validator/v10" | |
| ) | |
| func init() { | |
| env.Load(".env") | |
| } | |
| func main() { | |
| e := echo.New() | |
| e.Validator = &utils.CustomValidator{Validator: validator.New()} | |
| e.Logger.Fatal(e.Start("1234")) | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package utils | |
| import ( | |
| "unicode" | |
| "unicode/utf8" | |
| "github.com/go-playground/validator/v10" | |
| ) | |
| // CustomValidator is type setting of third party validator | |
| type CustomValidator struct { | |
| Validator *validator.Validate | |
| } | |
| // Init validator | |
| func (cv *CustomValidator) Init() { | |
| cv.Validator.RegisterValidation("password", func(fl validator.FieldLevel) bool { | |
| var ( | |
| hasNumber = false | |
| hasSpecialChar = false | |
| hasLetter = false | |
| hasSuitableLen = false | |
| ) | |
| password := fl.Field().String() | |
| if utf8.RuneCountInString(password) <= 30 && utf8.RuneCountInString(password) >= 6 { | |
| hasSuitableLen = true | |
| } | |
| for _, c := range password { | |
| switch { | |
| case unicode.IsNumber(c): | |
| hasNumber = true | |
| case unicode.IsPunct(c) || unicode.IsSymbol(c): | |
| hasSpecialChar = true | |
| case unicode.IsLetter(c) || c == ' ': | |
| hasLetter = true | |
| default: | |
| return false | |
| } | |
| } | |
| return hasNumber && hasSpecialChar && hasLetter && hasSuitableLen | |
| }) | |
| } | |
| // Validate Data | |
| func (cv *CustomValidator) Validate(i interface{}) error { | |
| return cv.Validator.Struct(i) | |
| } |
Author
@Shawnyeungcf
Look at this example : https://github.com/cjaewon/echo-gorm-example
Line 27 will always return true: If the RuneCountInString(password) is not smaller or equal 30 (thus bigger than 30) it is doomed to also be bigger than 6.
P.S. sorry if this comment is misplaced, I was looking at this piece of code while trying to understand another (unrelated) bug.
Author
@CSteigueber Thank you for your comments i will alter it.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
how can we integrate with db connection and check duplicate values in db?