golang gookit验证器无法与全局自定义验证器一起使用。

huangapple go评论82阅读模式
英文:

golang gookit validate does not work with global custom validator

问题

我正在尝试使用Go语言的go-kit验证器并添加自定义验证器,但是该函数从未被调用。

package main

import (
	"fmt"

	"github.com/gookit/validate"
)

type Sample struct {
	Name    string `json:"name" validate:"required"`
	Address 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", Address: "address", Payment: ""}
	v := validate.Struct(&s)
	res := v.Validate()
	if !res {
		fmt.Println(v.Errors.OneError())
	} else {
		fmt.Println("SUCCESS")
	}
}

结果始终为成功,并且自定义验证器从未被调用。可以直接在Go Playground上运行代码。

英文:

I am trying to use golang gookit validator and adding custom validator, but the function never got fired.

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 be always success and the custom validator never get called. Directly on go playground

答案1

得分: 0

你需要在config中明确指出,不要跳过空值,像下面这样:

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

然后运行代码,它就会起作用。

英文:

You need to explicitly mention in the config,

> not to skip empty values

like below:

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

Then, run the code, it will work

huangapple
  • 本文由 发表于 2023年7月16日 21:22:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/76698490.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定