Skip to content

Instantly share code, notes, and snippets.

@cjaewon
Last active April 17, 2023 00:08
Show Gist options
  • Select an option

  • Save cjaewon/dece2b4b7b4adc14a0d4b561276157c0 to your computer and use it in GitHub Desktop.

Select an option

Save cjaewon/dece2b4b7b4adc14a0d4b561276157c0 to your computer and use it in GitHub Desktop.
golang echo validator (password)
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"))
}
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)
}
@Shawnyeungcf
Copy link

how can we integrate with db connection and check duplicate values in db?

@cjaewon
Copy link
Author

cjaewon commented Sep 27, 2021

@CSteigueber
Copy link

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.

@cjaewon
Copy link
Author

cjaewon commented Jan 15, 2023

@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