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 ofnil
to bypass this issue. - Use a combined validation rule to compensate for the impact of default values on the
required
rule. For example, modifying the validation rule of theAge
attribute in the example above torequired|min:1
will achieve the desired business validation effect. - Use the
Assoc
joint validation method inStruct
validation to set joint validation parameters. When validating parameters of theStruct
type, the parameter values will be validated according to the parameters given in theAssoc
method. If using the framework'sServer
, with structuredAPI
input/output (XxxReq/XxxRes
), theServer
will automatically callAssoc
for validation, so developers need not worry about the impact of default values. Documentation link: Struct Validation - Assoc