first commit
This commit is contained in:
32
pkg/validator/rule.go
Normal file
32
pkg/validator/rule.go
Normal file
@ -0,0 +1,32 @@
|
||||
package validator
|
||||
|
||||
import (
|
||||
"github.com/go-playground/validator/v10"
|
||||
"regexp"
|
||||
"time"
|
||||
)
|
||||
|
||||
func isoPhone(fl validator.FieldLevel) bool {
|
||||
ok, _ := regexp.MatchString(`^\+(9[976]\d|8[987530]\d|6[987]\d|5[90]\d|42\d|3[875]\d|2[98654321]\d|9[8543210]|8[6421]|6[6543210]|5[87654321]|4[987654310]|3[9643210]|2[70]|7|1)\d{1,14}$`, fl.Field().String())
|
||||
return ok
|
||||
}
|
||||
|
||||
func chinesePhone(fl validator.FieldLevel) bool {
|
||||
ok, _ := regexp.MatchString(`^1[3-9]\d{9}$`, fl.Field().String())
|
||||
return ok
|
||||
}
|
||||
|
||||
func idCard(fl validator.FieldLevel) bool {
|
||||
isIdCard, _ := regexp.MatchString(`^[1-9]\d{7}((0\d)|(1[0-2]))(([0-2]\d)|3[0-1])\d{3}$|^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0-2]\d)|3[0-1])\d{3}(\d|X)$`, fl.Field().String())
|
||||
return isIdCard
|
||||
}
|
||||
|
||||
func chineseName(fl validator.FieldLevel) bool {
|
||||
var hzRegexp = regexp.MustCompile("^[\u4e00-\u9fa5]{2,8}$")
|
||||
return hzRegexp.MatchString(fl.Field().String())
|
||||
}
|
||||
|
||||
func year(fl validator.FieldLevel) bool {
|
||||
_, err := time.Parse("2006", fl.Field().String())
|
||||
return err == nil
|
||||
}
|
55
pkg/validator/validator.go
Normal file
55
pkg/validator/validator.go
Normal file
@ -0,0 +1,55 @@
|
||||
package validator
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"sync"
|
||||
|
||||
"github.com/gin-gonic/gin/binding"
|
||||
"github.com/go-playground/validator/v10"
|
||||
)
|
||||
|
||||
type DefaultValidator struct {
|
||||
once sync.Once
|
||||
validate *validator.Validate
|
||||
}
|
||||
|
||||
var Validator binding.StructValidator = &DefaultValidator{}
|
||||
|
||||
func (v *DefaultValidator) ValidateStruct(obj any) error {
|
||||
if kindOfData(obj) == reflect.Struct {
|
||||
|
||||
v.lazyinit()
|
||||
|
||||
if err := v.validate.Struct(obj); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (v *DefaultValidator) Engine() any {
|
||||
v.lazyinit()
|
||||
return v.validate
|
||||
}
|
||||
|
||||
func (v *DefaultValidator) lazyinit() {
|
||||
v.once.Do(func() {
|
||||
v.validate = validator.New()
|
||||
v.validate.SetTagName("validate")
|
||||
_ = v.validate.RegisterValidation("chinesePhone", chinesePhone)
|
||||
_ = v.validate.RegisterValidation("isoPhone", isoPhone)
|
||||
_ = v.validate.RegisterValidation("idCard", idCard)
|
||||
_ = v.validate.RegisterValidation("chineseName", chineseName)
|
||||
_ = v.validate.RegisterValidation("year", year)
|
||||
})
|
||||
}
|
||||
|
||||
func kindOfData(data any) reflect.Kind {
|
||||
value := reflect.ValueOf(data)
|
||||
valueType := value.Kind()
|
||||
|
||||
if valueType == reflect.Ptr {
|
||||
valueType = value.Elem().Kind()
|
||||
}
|
||||
return valueType
|
||||
}
|
Reference in New Issue
Block a user