asaskevich / govalidator

[Go] Package of validators and sanitizers for strings, numerics, slices and structs
MIT License
6.05k stars 555 forks source link

implement ValidateMap #338

Closed mie00 closed 4 years ago

mie00 commented 5 years ago

Adds ValidateMap which can be used to validate map[string]interface{} against a validation map in the form map[string]interface{}. The validation map values can be either a string in the same form as the tags used in structs (without the key valid) or a map[string]interface{} for recursive validation. The map to be validated can contain values of any kind.

Example usage added in the README (copied from #224)

var mapTemplate = map[string]interface{}{
    "name":"required,alpha",
    "family":"required,alpha",
    "email":"required,email",
    "cell-phone":"numeric",
    "address":map[string]interface{}{
        "line1":"required,alphanum",
        "line2":"alphanum",
        "postal-code":"numeric",
    },
}
 var inputMap = map[string]interface{}{
    "name":"Bob",
    "family":"Smith",
    "email":"foo@bar.baz",
    "address":map[string]interface{}{
        "line1":"1234",
        "line2":"",
        "postal-code":"",
    },
}
 result, err := govalidator.ValidateMap(mapTemplate, inputMap)
if err != nil {
    println("error: " + err.Error())
}
println(result)

It also adds custom tag type(type) to validate map values of type interface{}. However, it can be used with any type. Example of types it can take:

string
int
*int
**int
map[string]string
map[string]interface{}
[][]int

fixes #224

asaskevich commented 4 years ago

Thank you very much, you did huge work!