Validator: how to validate field value inside 3-rd party structure?

Created on 7 Dec 2017  路  4Comments  路  Source: go-playground/validator

Package version eg. v8, v9:

v9

Issue, Question or Enhancement:

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?

Code sample, to showcase or reproduce:

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"`
}

All 4 comments

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.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

alexyans picture alexyans  路  3Comments

0505gonzalez picture 0505gonzalez  路  3Comments

ivybridge-3c33 picture ivybridge-3c33  路  3Comments

puellanivis picture puellanivis  路  5Comments

anam-digicom picture anam-digicom  路  4Comments