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

golang gookit validate does not work with global custom validators

PHPz
Release: 2024-02-14 14:42:16
forward
765 people have browsed it

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")
    }
}
Copy after login

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
})
Copy after login

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!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template