library-go/validator/validate.go

51 lines
859 B
Go
Raw Permalink Normal View History

package required
import (
"fmt"
2024-08-20 15:33:20 +00:00
"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
}