feat: finish member func

This commit is contained in:
daniel.w 2024-08-02 09:39:58 +08:00
parent 7f25d329e4
commit ed69cc2367
2 changed files with 32 additions and 19 deletions

View File

@ -1,10 +1,22 @@
package required package required
import "github.com/go-playground/validator/v10" import (
"fmt"
"github.com/go-playground/validator/v10"
)
type Validate interface {
ValidateAll(obj any) error
BindToValidator(opts ...Option) error
}
type Validator struct {
V *validator.Validate
}
// ValidateAll TODO 要移到common 包 // ValidateAll TODO 要移到common 包
func ValidateAll(validate *validator.Validate, obj any) error { func (v *Validator) ValidateAll(obj any) error {
err := validate.Struct(obj) err := v.V.Struct(obj)
if err != nil { if err != nil {
return err return err
} }
@ -12,10 +24,23 @@ func ValidateAll(validate *validator.Validate, obj any) error {
return nil return nil
} }
func MustValidator(option ...Option) *validator.Validate { func (v *Validator) BindToValidator(opts ...Option) error {
// TODO Validator 要抽出來 for _, item := range opts {
v := validator.New() err := v.V.RegisterValidation(item.ValidatorName, item.ValidatorFunc)
err := BindToValidator(v, option...) if err != nil {
return fmt.Errorf("failed to register validator : %w", err)
}
}
return nil
}
func MustValidator(option ...Option) Validate {
v := &Validator{
V: validator.New(),
}
err := v.BindToValidator(option...)
if err != nil { if err != nil {
// log // log
} }

View File

@ -1,7 +1,6 @@
package required package required
import ( import (
"fmt"
"regexp" "regexp"
"github.com/go-playground/validator/v10" "github.com/go-playground/validator/v10"
@ -12,17 +11,6 @@ type Option struct {
ValidatorFunc func(fl validator.FieldLevel) bool ValidatorFunc func(fl validator.FieldLevel) bool
} }
func BindToValidator(v *validator.Validate, opts ...Option) error {
for _, item := range opts {
err := v.RegisterValidation(item.ValidatorName, item.ValidatorFunc)
if err != nil {
return fmt.Errorf("failed to register validator : %w", err)
}
}
return nil
}
// WithAccount 創建一個新的 Option 結構,包含自定義的驗證函數,用於驗證 email 和台灣的手機號碼格式 // WithAccount 創建一個新的 Option 結構,包含自定義的驗證函數,用於驗證 email 和台灣的手機號碼格式
func WithAccount(tagName string) Option { func WithAccount(tagName string) Option {
return Option{ return Option{