51 lines
859 B
Go
51 lines
859 B
Go
package required
|
|
|
|
import (
|
|
"fmt"
|
|
|
|
"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
|
|
}
|