Impact of Struct Default Values on the required Rule
The properties of a Struct have default values, which in some cases can cause the required rule to become ineffective. For example:
type User struct {
Name string `v:"required"`
Age uint `v:"required"`
}
In this structure validation, the required check for the Age property will fail because Age will have a default value of 0 even if no input is provided.
There are three solutions:
- Change the attribute to a pointer type, such as
*int,*float64,*g.Var, etc., taking advantage of the pointer type's default value ofnilto bypass this issue. - Use a combined validation rule to compensate for the impact of default values on the
requiredrule. For example, modifying the validation rule of theAgeattribute in the example above torequired|min:1will achieve the desired business validation effect. - Use the
Assocjoint validation method inStructvalidation to set joint validation parameters. When validating parameters of theStructtype, the parameter values will be validated according to the parameters given in theAssocmethod. If using the framework'sServer, with structuredAPIinput/output (XxxReq/XxxRes), theServerwill automatically callAssocfor validation, so developers need not worry about the impact of default values. Documentation link: Struct Validation - Assoc