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
CodePudding user response:
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)
}
}