validatorcheckervalidator


使用例子:tag 与 Rule的比较

validator使用的tag,与checker的Rule的对应关系可以参考README文档。

checkerSliceArrayMap

自定义校验规则

使用validator

validatoris-awesome
  1. package main


  2. import (

  3. "fmt"


  4. "github.com/go-playground/validator/v10"

  5. )


  6. // MyStruct ..

  7. type MyStruct struct {

  8. String string `validate:"is-awesome"`

  9. }


  10. // use a single instance of Validate, it caches struct info

  11. var validate *validator.Validate


  12. func main() {

  13. validate = validator.New()

  14. validate.RegisterValidation("is-awesome", ValidateMyVal)


  15. s := MyStruct{String: "not awesome"}

  16. err := validate.Struct(s)

  17. if err != nil {

  18. fmt.Printf("%v", err)

  19. }

  20. }


  21. // ValidateMyVal implements validator.Func

  22. func ValidateMyVal(fl validator.FieldLevel) bool {

  23. return fl.Field().String() == "awesome"

  24. }

打印出来的错误信息是:

  1. Key: 'MyStruct.String' Error:Field validation for 'String' failed on the 'is-awesome' tag

使用checker

  1. package main


  2. import (

  3. "fmt"


  4. "github.com/liangyaopei/checker"

  5. )


  6. type MyStruct struct {

  7. String string

  8. }


  9. type isAwesomeRule struct {

  10. FieldExpr string

  11. }


  12. func (r isAwesomeRule) Check(param interface{}) (bool, string) {

  13. exprValue, _ := checker.FetchFieldInStruct(param, r.FieldExpr)

  14. exprStr := exprValue.(string)

  15. if exprStr != "awesome" {

  16. return false, fmt.Sprintf("'%s' has worng value", r.FieldExpr)

  17. }

  18. return true, ""

  19. }


  20. func main() {

  21. s := MyStruct{String: "not awesome"}

  22. ch := checker.NewChecker()

  23. rule := isAwesomeRule{FieldExpr: "String"}

  24. ch.Add(rule, "value is not awesome")


  25. isValid, prompt, errMsg := ch.Check(s)

  26. if !isValid {

  27. fmt.Printf("prompt:%s,errMsg:%s", prompt, errMsg)

  28. }

  29. }

使用checker,不需要在结构体上添加校验标签,逻辑更加清晰。更多自定义规则的例子在这里。

定制错误信息

使用validator

validatortranslator
  1. import (

  2. "fmt"


  3. "github.com/go-playground/locales/en"

  4. ut "github.com/go-playground/universal-translator"

  5. "github.com/go-playground/validator/v10"

  6. en_translations "github.com/go-playground/validator/v10/translations/en"

  7. )


  8. var (

  9. uni *ut.UniversalTranslator

  10. validate *validator.Validate

  11. )


  12. func main() {


  13. // NOTE: ommitting allot of error checking for brevity


  14. en := en.New()

  15. uni = ut.New(en, en)


  16. // this is usually know or extracted from http 'Accept-Language' header

  17. // also see uni.FindTranslator(...)

  18. trans, _ := uni.GetTranslator("en")


  19. validate = validator.New()

  20. en_translations.RegisterDefaultTranslations(validate, trans)


  21. translateOverride(trans)

  22. }


  23. func translateOverride(trans ut.Translator) {


  24. validate.RegisterTranslation("required", trans, func(ut ut.Translator) error {

  25. return ut.Add("required", "{0} must have a value!", true) // see universal-translator for details

  26. }, func(ut ut.Translator, fe validator.FieldError) string {

  27. t, _ := ut.T("required", fe.Field())


  28. return t

  29. })

  30. ....

  31. }

使用checker

checkerprompt
  1. func (c *ruleChecker) Add(rule Rule, prompt string) {

  2. c.rules = append(c.rules, rule)

  3. c.prompts = append(c.prompts, prompt)

  4. }

valueisnotawesome
  1. ch.Add(rule, "value is not awesome")

  2. isValid, prompt, errMsg := ch.Check(s)

checker易做,validator难做

validator

更改第三方包结构体的校验规则

ParamParam18<=age<=80
  1. package thrid_party


  2. type Param struct{

  3. Age `validate:"min=18,max=80"`

  4. }

validatorthird_partyParam
  1. package main


  2. func validate(p thrid_party.Param)(isValid bool){

  3. ....

  4. }

checker
  1. rule := checker.NewRangeRuleInt("Age", 20, 80)

  2. checker.Add(rule, "invlaid age")

checker

自引用的结构体校验

假设需要校验链表的长度,完整的例子在这里

  1. type list struct {

  2. Name *string

  3. Next *list `validate:"nonzero"`

  4. }

Nextvalidator
checker
  1. name := "list"

  2. node1 := list{Name: &name, Next: nil}

  3. lists := list{Name: &name, Next: &node1}


  4. listChecker := checker.NewChecker()

  5. nameRule := checker.NewLengthRule("Next.Name", 1, 20)

  6. listChecker.Add(nameRule, "invalid info name")

Next.Name

我的公众号:lyp分享的地方

我的知乎专栏: https://zhuanlan.zhihu.com/c_1275466546035740672

我的博客:www.liangyaopei.com

Github Page: https://liangyaopei.github.io/