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
}

测试生效

 

posted @ 2021-06-13 18:28  青花メ  阅读(950)  评论(0编辑  收藏  举报