52 lines
899 B
Go
52 lines
899 B
Go
|
package required
|
||
|
|
||
|
import (
|
||
|
"fmt"
|
||
|
|
||
|
"github.com/zeromicro/go-zero/core/logx"
|
||
|
|
||
|
"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(),
|
||
|
}
|
||
|
|
||
|
if err := v.BindToValidator(option...); err != nil {
|
||
|
logx.Error("failed to bind validator")
|
||
|
}
|
||
|
|
||
|
return v
|
||
|
}
|