Home  >  Article  >  Backend Development  >  golang gookit validate does not work with global custom validators

golang gookit validate does not work with global custom validators

PHPz
PHPzforward
2024-02-14 14:42:16673browse

golang gookit validate 不适用于全局自定义验证器

php editor Banana discovered a problem when using golang's gookit validate, that is, it does not apply to global custom validators. gookit validate is a convenient and powerful validation library that provides many built-in validation rules, but there are some limitations in supporting global custom validation rules. This may cause some trouble for developers, so you need to pay attention to this when using gookit validate. Next, we'll explore this issue in detail and provide some solutions.

Question content

I'm trying to use the golang gookit validator and add a custom validator, but the function never gets triggered.

package main

import (
    "fmt"

    "github.com/gookit/validate"
)

type Sample struct {
    Name    string `json:"name" validate:"required"`
    Addres  string `json:"address" validate:"required"`
    Payment string `json:"payment" validate:"payment_method"`
}

func main() {
    validate.AddValidator("payment_method", func(val interface{}) bool {
        value, ok := val.(string)
        fmt.Println(value)
        if !ok {
            return false
        }
        if value != "hello" {
            return false
        }
        return true
    })
    s := Sample{Name: "name", Addres: "address", Payment: ""}
    v := validate.Struct(&s)
    res := v.Validate()
    if !res {
        fmt.Println(v.Errors.OneError())
    } else {
        fmt.Println("SUCCESS")
    }
}

The result will always be successful and the custom validator will never be called. Directly on the go playground

Workaround

You need to mention this explicitly in the configuration,

Do not skip null values

As follows:

validate.Config(func(opt *validate.GlobalOption) {
        opt.SkipOnEmpty = false
})

Then, run the code and it will work

The above is the detailed content of golang gookit validate does not work with global custom validators. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete