php editor Xiaoxin today introduces to you a powerful Golang validator - custom enumeration verification rules. As Golang becomes more popular, more and more developers are starting to use it to build efficient and reliable applications. The validator is one of the important tools, which can help us verify whether the input data conforms to the specified format and requirements. Custom enumeration validation rules are an important function of the validator, which can help us define our own enumeration types and validate the input data. Through this article, we will introduce in detail how to use custom enumeration validation rules in Golang, as well as some practical application scenarios. Let’s explore this powerful feature together!
I am using https://github.com/go-playground/validator and I need to create custom validation rules for different enumeration values. Here is my structure - https://go.dev/play/p/UmR6YH6cvK9. As you can see, I have 3 different user types: admins, moderators, and content creators, and I want to adjust different password rules for them. For example, an administrator's password should be at least 7 characters long, and a moderator's password should be at least 5 characters long. Is it possible to do this via tags in go-playground/validator?
My service gets a list of users and needs to use different rules for validation
You can add a method to usertype
that uses validator
package to authenticate 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 looks 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) } }
The above is the detailed content of Golang validator custom enumeration validation rules. For more information, please follow other related articles on the PHP Chinese website!