Home > database >  how to skip json validation for an empty array via Golang
how to skip json validation for an empty array via Golang

Time:02-27

I'd like to skip validation for empty arrays in a json file for a specific field. Below you can see Book structs definition, which could be validated if no authors are declared in json file. On the other hand it fails if an empty array is defined for authors. Is it possible to achieve this behavior with existing tags, or do I have to define custom validator?

type Book struct {
    Title      string `json:"title" validate:"min=2"`
    Authors    `json:"authors" validate:"omitempty,min=1,dive,min=3"`
    // ...
}

I'm validating Book struct via "github.com/go-playground/validator/v10" package's validator:

    book := &Book{}
    if err := json.Unmarshal(data, book); err != nil {
        return nil, err
    }

    v := validator.New()
    if err := v.Struct(book); err != nil {
        return nil, err
    }

Works:

{
    "title": "A Book"
}

Fails with "Key: 'Book.Authors' Error:Field validation for 'Authors' failed on the 'min' tag"

{
    "title": "A Book",
    "authors": []

}

CodePudding user response:

It's because your Authors validation string is "omitempty,min=1,dive,min=3". The length of an empty slice is 0, which is <1.

If you replace the validation string with "omitempty,min=0,dive,min=3" instead, it'll pass.

  • Related