I'm using GoLang Validator on a struct to validate its fields. Even though I don't add required
tag, it still behaves as if it is required.
type Order struct {
// ... other fields
UserID string `json:"userId" validate:"uuid4"`
// ... other fields
}
if err = validator.New().Struct(i); err != nil {
return err
}
Output: User ID: unknown error
It is not required hence the value is zero-value but it still returns an error. Am I doing something wrong here?
You should add the omitempty
validator to allow empty values. Try out the code below on Go playground .
type Order struct {
// ... other fields
UserID string `json:"omitempty,userId" validate:"omitempty,uuid4"`
// ... other fields
}
if err := validator.New().Struct(Order{}); err != nil {
return err
}
Note that to marshal the struct to JSON you also need to set the omitempty
validator if you want to allow empty values...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.