GIn 自定义validator 使用binding还是validate的问题

github.com/gin-gonic/gin v1.7.2
关于validator
// Validator is the default validator which implements the StructValidator
// interface. It uses https://github.com/go-playground/validator/tree/v8.18.2
// under the hood.
var Validator StructValidator = &defaultValidator{}
type UserLoginInput struct {
    UserName string`json:"username" form:"username" comment:"姓名" binding:"required,my_validator"`
    PassWord string`json:"password" form:"password" comment:"密码"  binding:"required"`
}

升级到V10

github.com/go-playground/validator/v10 v10.6.1
package public

import (
    "fmt"
    "github.com/gin-gonic/gin/binding"
    validator2 "github.com/go-playground/validator/v10"
)

func InitVali() {
    v, ok := binding.Validator.Engine().(*validator2.Validate)
    if ok {
        // 自定义验证方法
        _ = v.RegisterValidation("my_validator", checkName)
    }
}


func checkName(fl validator2.FieldLevel) bool {
    field := fl.Field().String()
    fmt.Print(field)
    return false
}

测试生效

 

上一篇:Gin框架beego的使用


下一篇:golang-go mod版本等相关内容: