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

2021/6/13 18:52:14

本文主要是介绍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 自定义validator 使用binding还是validate的问题的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程