feature/validator #4

Merged
daniel.w merged 2 commits from feature/validator into main 2024-08-19 17:21:53 +00:00
3 changed files with 104 additions and 0 deletions
Showing only changes of commit 1c00bf7eda - Show all commits

26
validator/go.mod Normal file
View File

@ -0,0 +1,26 @@
module code.30cm.net/digimon/library-go/validator
go 1.22.3
require (
github.com/go-playground/validator/v10 v10.22.0
github.com/zeromicro/go-zero v1.7.0
)
require (
github.com/fatih/color v1.17.0 // indirect
github.com/gabriel-vasile/mimetype v1.4.3 // indirect
github.com/go-playground/locales v0.14.1 // indirect
github.com/go-playground/universal-translator v0.18.1 // indirect
github.com/leodido/go-urn v1.4.0 // indirect
github.com/mattn/go-colorable v0.1.13 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/spaolacci/murmur3 v1.1.0 // indirect
go.opentelemetry.io/otel v1.24.0 // indirect
go.opentelemetry.io/otel/trace v1.24.0 // indirect
go.uber.org/automaxprocs v1.5.3 // indirect
golang.org/x/crypto v0.25.0 // indirect
golang.org/x/net v0.27.0 // indirect
golang.org/x/sys v0.22.0 // indirect
golang.org/x/text v0.16.0 // indirect
)

49
validator/validate.go Normal file
View File

@ -0,0 +1,49 @@
package required
import (
"fmt"
"github.com/go-playground/validator/v10"
"github.com/zeromicro/go-zero/core/logx"
)
type Validate interface {
ValidateAll(obj any) error
BindToValidator(opts ...Option) error
}
type Validator struct {
V *validator.Validate
}
func (v *Validator) ValidateAll(obj any) error {
err := v.V.Struct(obj)
if err != nil {
return err
}
return nil
}
func (v *Validator) BindToValidator(opts ...Option) error {
for _, item := range opts {
err := v.V.RegisterValidation(item.ValidatorName, item.ValidatorFunc)
if err != nil {
return fmt.Errorf("failed to register validator : %w", err)
}
}
return nil
}
func MustValidator(option ...Option) Validate {
v := &Validator{
V: validator.New(),
}
if err := v.BindToValidator(option...); err != nil {
logx.Error("failed to bind validator")
}
return v
}

View File

@ -0,0 +1,29 @@
package required
import (
"regexp"
"github.com/go-playground/validator/v10"
)
type Option struct {
ValidatorName string
ValidatorFunc func(fl validator.FieldLevel) bool
}
// WithAccount 創建一個新的 Option 結構,包含自定義的驗證函數,用於驗證 email 和台灣的手機號碼格式
func WithAccount(tagName string) Option {
return Option{
ValidatorName: tagName,
ValidatorFunc: func(fl validator.FieldLevel) bool {
value := fl.Field().String()
emailRegex := `^[a-z0-9._%+\-]+@[a-z0-9.\-]+\.[a-z]{2,}$`
phoneRegex := `^(\+886|0)?9\d{8}$`
emailMatch, _ := regexp.MatchString(emailRegex, value)
phoneMatch, _ := regexp.MatchString(phoneRegex, value)
return emailMatch || phoneMatch
},
}
}