feat/member #1

Merged
daniel.w merged 5 commits from feat/member into main 2024-08-02 02:20:17 +00:00
2 changed files with 32 additions and 19 deletions
Showing only changes of commit ed69cc2367 - Show all commits

View File

@ -1,10 +1,22 @@
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 包
func ValidateAll(validate *validator.Validate, obj any) error {
err := validate.Struct(obj)
func (v *Validator) ValidateAll(obj any) error {
err := v.V.Struct(obj)
if err != nil {
return err
}
@ -12,10 +24,23 @@ func ValidateAll(validate *validator.Validate, obj any) error {
return nil
}
func MustValidator(option ...Option) *validator.Validate {
// TODO Validator 要抽出來
v := validator.New()
err := BindToValidator(v, option...)
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(),
}
err := v.BindToValidator(option...)
if err != nil {
// log
}

View File

@ -1,7 +1,6 @@
package required
import (
"fmt"
"regexp"
"github.com/go-playground/validator/v10"
@ -12,17 +11,6 @@ type Option struct {
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 和台灣的手機號碼格式
func WithAccount(tagName string) Option {
return Option{