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

50 lines
823 B
Go

package required
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 (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(),
}
err := v.BindToValidator(option...)
if err != nil {
// log
}
return v
}