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

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

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包来验证用户。

  1. type UserType int
  2. const (
  3. Admin UserType = iota
  4. Moderator
  5. ContentCreator
  6. )
  7. func (u UserType) Validate() error {
  8. switch u {
  9. case Admin:
  10. // 验证管理员
  11. case Moderator:
  12. // 验证版主
  13. case ContentCreator:
  14. // 验证内容创作者
  15. default:
  16. return fmt.Errorf("无效的用户类型")
  17. }
  18. return nil
  19. }

调用验证的方式如下:

  1. func main() {
  2. a := User{
  3. Type: Admin,
  4. Name: "admin",
  5. Password: "pass",
  6. LastActivity: time.Time{},
  7. }
  8. err := a.Type.Validate()
  9. if err != nil {
  10. fmt.Println("无效的用户:%w", err)
  11. }
  12. }
英文:

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

  1. type UserType int
  2. const (
  3. Admin UserType = iota
  4. Moderator
  5. ContentCreator
  6. )
  7. func (u UserType) Validate() error {
  8. switch u {
  9. case Admin:
  10. // validate admin
  11. case Moderator:
  12. // validate moderator
  13. case ContentCreator:
  14. // validate content creator
  15. default:
  16. return fmt.Errorf("invalid user type")
  17. }
  18. return nil
  19. }

Calling validate would look something like this

  1. func main() {
  2. a := User{
  3. Type: Admin,
  4. Name: "admin",
  5. Password: "pass",
  6. LastActivity: time.Time{},
  7. }
  8. err := a.Type.Validate()
  9. if err != nil {
  10. fmt.Println("invalid user: %w", err)
  11. }
  12. }

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:

确定