67 lines
1.5 KiB
Go
67 lines
1.5 KiB
Go
|
package irisutils
|
||
|
|
||
|
import (
|
||
|
"regexp"
|
||
|
|
||
|
"github.com/go-playground/validator/v10"
|
||
|
)
|
||
|
|
||
|
type ValidationError struct {
|
||
|
Field string `json:"field"`
|
||
|
Tag string `json:"tag"`
|
||
|
}
|
||
|
|
||
|
var Validator = validator.New()
|
||
|
var usernamePattern *regexp.Regexp
|
||
|
var alphaNumExtra *regexp.Regexp
|
||
|
var passNumber *regexp.Regexp
|
||
|
var passLower *regexp.Regexp
|
||
|
var passUpper *regexp.Regexp
|
||
|
var passSign *regexp.Regexp
|
||
|
|
||
|
func init() {
|
||
|
usernamePattern = regexp.MustCompile(`^[a-zA-Z][a-zA-Z0-9\._-]{4,}$`)
|
||
|
passNumber = regexp.MustCompile(`.*\d.*`)
|
||
|
passLower = regexp.MustCompile(`.*[a-z].*`)
|
||
|
passUpper = regexp.MustCompile(`.*[A-Z].*`)
|
||
|
passSign = regexp.MustCompile(`.*[*\.!@#$%^&\(\)\{\}\[\]:";'<>,?/~_\+\-=|\\]+.*`)
|
||
|
alphaNumExtra = regexp.MustCompile(`^[a-zA-Z0-9_\-\.]*$`)
|
||
|
Validator.RegisterValidation("username", ValidateUsername)
|
||
|
Validator.RegisterValidation("password", ValidatePassword)
|
||
|
Validator.RegisterValidation("alphaNumExtra", ValidateAlphaNumExtra)
|
||
|
}
|
||
|
|
||
|
func ValidateAlphaNumExtra(fl validator.FieldLevel) bool {
|
||
|
return alphaNumExtra.MatchString(fl.Field().String())
|
||
|
}
|
||
|
|
||
|
func ValidateUsername(fl validator.FieldLevel) bool {
|
||
|
return usernamePattern.MatchString(fl.Field().String())
|
||
|
}
|
||
|
|
||
|
func ValidatePassword(fl validator.FieldLevel) bool {
|
||
|
count := 0
|
||
|
pass := fl.Field().String()
|
||
|
|
||
|
if len(pass) >= 6 && len(pass) <= 256 {
|
||
|
|
||
|
if passNumber.MatchString(pass) {
|
||
|
count++
|
||
|
}
|
||
|
|
||
|
if passLower.MatchString(pass) {
|
||
|
count++
|
||
|
}
|
||
|
|
||
|
if passUpper.MatchString(pass) {
|
||
|
count++
|
||
|
}
|
||
|
|
||
|
if passSign.MatchString(pass) {
|
||
|
count++
|
||
|
}
|
||
|
}
|
||
|
|
||
|
return count >= 3
|
||
|
}
|