asaskevich / govalidator

[Go] Package of validators and sanitizers for strings, numerics, slices and structs
MIT License
5.97k stars 554 forks source link

Custom function validation doesn't work #479

Closed mycode65678 closed 1 year ago

mycode65678 commented 1 year ago

main.go

package main

import (
    "fmt"
    "github.com/asaskevich/govalidator"
    "github.com/gin-gonic/gin/binding"
    "github.com/gin-gonic/gin"
    "os"
    "os/signal"
    "reflect"
)

type customValidator struct{}

func (c *customValidator) ValidateStruct(ptr interface{}) error {
    // after

    // after
    govalidator.CustomTypeTagMap.Set("customGoogle", func(i interface{}, o interface{}) bool {
        // ...
        fmt.Println("customGoogle Set CustomTypeTagMap")
        return false
    })
    govalidator.TagMap["customGoogle"] = govalidator.Validator(func(str string) bool {
        fmt.Println("customGoogle TagMap")
        return str == "duck"
    })
    govalidator.ParamTagMap["customGoogle"] = govalidator.ParamValidator(func(str string, params ...string) bool {
        fmt.Println("customGoogle ParamTagMap")
        return false
    })
    govalidator.ParamTagMap["customGoogle"] = govalidator.ParamValidator(func(str string, params ...string) bool {
        fmt.Println("customGoogle ParamTagMap", str, params)
        res := reflect.ValueOf(ptr).Elem().FieldByName(params[0]).Interface().(string)
        return str == res
    })
    if _, err := govalidator.ValidateStruct(ptr); err != nil {
        return err
    }
    return nil
}

func (c *customValidator) Engine() interface{} {
    return nil
}

type PlayKindUpdate struct {
    // Code
    Google string `form:"Google" valid:"customGoogle"`
}

func  Test(c *gin.Context) {
    var in PlayKindUpdate
    if err := c.ShouldBind(&in); err != nil {
        fmt.Println(err)
        return
    }
}

func main() {
    binding.Validator = &customValidator{}
       r := gin.Default()
        r.POST("/test",Test)
        r.Run("0.0.0.0:9000")
    c := make(chan os.Signal, 1)
    signal.Notify(c, os.Interrupt, os.Kill)
    <-c
}

The code above doesn't print the information I need, saying that the custom function is not running