go-playground / validator

:100:Go Struct and Field validation, including Cross Field, Cross Struct, Map, Slice and Array diving
MIT License
16.41k stars 1.3k forks source link

Add type validation - useful for ValidateMap #1089

Open arxeiss opened 1 year ago

arxeiss commented 1 year ago

Package version eg. v9, v10:

v10

Issue, Question or Enhancement:

I can validate the value, but not its type. Especially, when using ValidateMap and not validating on the Struct field (which has type), it might be useful.

I'm building a tool, which will work like a validation proxy. But the incoming structure is not known during compile time, because it is configurable. Here is the story

  1. Admin creates validation in JSON format, saves to DB, and assigns for an endpoint.
  2. 3rd party app will send JSON data to that endpoint.
  3. My app unmarshall that JSON into map[string]interface{} (here I don't know incoming structure during compile time).
  4. Load rules from DB.
  5. Calls v.ValidateMap

The issue is, that I can specify that field must be of some format (number/boolean). But I cannot force that the field is really number or just numeric string / bool or just "true" or "false" as string.

Code sample, to showcase or reproduce:

data := make(map[string]interface{})
// Here I cannot validate if `created_at` is number 1680699651 or string with digits "1680699651"
_ = json.Unmarshal([]byte(`{"created_at": 1680699651}`), &data)

res = v.ValidateMap(
    data,
    map[string]interface{}{
        "created_at": "number",
    },
)