【问题标题】:How can I transform a Go validator.FieldLevel.Field() to string array如何将 Go validator.FieldLevel.Field() 转换为字符串数组
【发布时间】:2020-05-28 00:37:02
【问题描述】:

我有一个具有这种结构的复杂对象。

type People struct {
    Objectives    []string  `validate:"required,ValidateCustom" json:"Objectives"`
}

我需要使用gopkg.in/go-playground/validator.v9 测试枚举中的列表思考:

//ValidateCustom -- ValidateCustom
func ValidateCustom(field validator.FieldLevel) bool {
    switch strings.ToUpper(field.Field().String()) {
    case "emumA":
    case "enumB":
        return true
    default:
        return false
    }
}

这个例子使用了字符串的概念,但是我如何构建到 []string 来迭代呢?

【问题讨论】:

  • 什么是validator
  • 它是实体的 gopkg 验证器... gopkg.in/go-playground/validator.v9

标签: arrays validation go go-playground


【解决方案1】:

我找到了答案...使用切片和接口

//ValidateCustom -- ValidateCustom
func ValidateCustom(field validator.FieldLevel) bool {
  inter := field.Field()
  slice, ok := inter.Interface().([]string)
  if !ok {
      return false
  }
  for _, v := range slice {
      switch strings.ToUpper(v) {
         case "enumA":
         case "enumB":
           return true
         default:
           return false
     }
}

【讨论】:

    猜你喜欢
    • 2017-05-20
    • 2017-03-30
    • 2021-08-29
    • 2019-04-29
    • 2021-12-13
    • 1970-01-01
    • 2014-12-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多