Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to skip json validation for an empty array via Golang

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": []

}

like image 754
icaptan Avatar asked Oct 29 '25 13:10

icaptan


1 Answers

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.

like image 190
j3st Avatar answered Oct 31 '25 03:10

j3st



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!