ark-member/internal/lib/required/validate_option.go

42 lines
1022 B
Go
Raw Normal View History

2024-07-21 15:57:56 +00:00
package required
import (
"fmt"
"regexp"
"github.com/go-playground/validator/v10"
)
type Option struct {
ValidatorName string
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{
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
},
}
}