v9
I have structure that contains sql.NullFloat64 as field Latitude, for example.
I want Float64 value inside sql.NullFloat64 to be in range [-90; 90] in case of latitude.
Is there a way to enforce validation for Float64 field inside sql.NullFloat64 structure with validate tag? Or should I create custom type/validator for this?
type NullFloat64 struct {
Float64 float64
Valid bool // Valid is true if Float64 is not NULL
}
type DeviceMetadata struct {
Description string `json:"description" validate:"max=65535"`
Model string `json:"model" validate:"max=100"`
//how to validate Latitude.Float64 value here?
Latitude sql.NullFloat64 `json:"latitude" validate:"lte=90,gte=-90,omitempty"`
Longitude sql.NullFloat64 `json:"longitude" validate:"lte=180,gte=-180,omitempty"`
}
Hey @gwan284
You just need to register a CustomTypeFunc so that validator knows what to do about that type, there is an example of almost exactly what you want https://github.com/go-playground/validator/blob/v9/_examples/custom/main.go
Validator just uses that function so you can return the underlying value you wish to validate, in your case a float64.
Please let me know if this helps, or you have any other questions :)
Thank you for response!
So CustomTypeFunc function defines how to take underlying value from type for all values of that type met.
What if I have different rules for usages of sql.NullFloat64 in another structs? Can this "ValueTaker" to be defined per object?
It knows how to extract for all values you've registered the type with; unfortunately there isn't a way to specify different behaviour per object using this... however if that is needed, you can register a StructLevel validation to treat structs differently, see here for the example.
Thanks for response again. Now it's absolutely clear.