Golang验证器自定义验证规则用于枚举类型

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

Golang validator custom validation rules for enum

问题

我正在使用https://github.com/go-playground/validator,并且我需要为不同的枚举值创建自定义验证规则。这是我的结构-https://go.dev/play/p/UmR6YH6cvK9。正如你所看到的,我有3种不同的用户类型:管理员、版主和内容创建者,我想为它们调整不同的密码规则。例如,管理员的密码长度应至少为7个字符,而版主的密码长度应至少为5个字符。是否可以通过go-playground/validator中的标签来实现这一点?

我的服务接收用户列表,并需要使用不同的规则进行验证。

英文:

I am using https://github.com/go-playground/validator and I need to create custom validation rules for different enum values. Here are my structures - https://go.dev/play/p/UmR6YH6cvK9. As you can see I have 3 different user types Admin, Moderator and Content creator and I want to adjust different password rules for them. For example admins, password length should be at least 7 symbols while Moderators should be at least 5. Is it possible to do this via tags in go-playground/validator?

My service gets List Of user and need to do validation with different rules

答案1

得分: 2

你可以为UserType添加一个方法,使用validator包来验证用户。

type UserType int

const (
    Admin UserType = iota
    Moderator
    ContentCreator
)

func (u UserType) Validate() error {
    switch u {
    case Admin:
        // 验证管理员
    case Moderator:
        // 验证版主
    case ContentCreator:
        // 验证内容创作者
    default:
        return fmt.Errorf("无效的用户类型")
    }
    return nil
}

调用验证的方式如下:

func main() {
    a := User{
        Type:         Admin,
        Name:         "admin",
        Password:     "pass",
        LastActivity: time.Time{},
    }

    err := a.Type.Validate()
    if err != nil {
        fmt.Println("无效的用户:%w", err)
    }
}
英文:

You can add a method to UserType that uses the validator package to validate the users.

type UserType int

const (
    Admin UserType = iota
    Moderator
    ContentCreator
)

func (u UserType) Validate() error {
    switch u {
    case Admin:
        // validate admin
    case Moderator:
        // validate moderator
    case ContentCreator:
        // validate content creator
    default:
        return fmt.Errorf("invalid user type")
    }
    return nil
}

Calling validate would look something like this

func main() {
    a := User{
        Type:         Admin,
        Name:         "admin",
        Password:     "pass",
        LastActivity: time.Time{},
    }

    err := a.Type.Validate()
    if err != nil {
        fmt.Println("invalid user: %w", err)
    }
}

huangapple
  • 本文由 发表于 2022年12月18日 01:29:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/74836077.html
匿名

发表评论

匿名网友

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

确定