jellydator / validation

An idiomatic validation package. Supports configurable and extensible validation rules (validators) using normal language constructs instead of error-prone struct tags.
MIT License
39 stars 6 forks source link

Possible to have "default validation" for structs? #3

Closed PMcca closed 1 year ago

PMcca commented 2 years ago

Sorry if this is a dumb question, but I've not found a way of doing this.

I have a struct like:

type Foo struct {
    A string
    B int
    C Bar
}

I would like to ensure that Foo (and any subsequent structs like Bar) do not have any empty fields. i.e. something like:

f := Foo {} // All fields are 0-valued

if err := validation.Validate(&f, validation.Required); err != nil {
        log.Fatal(err)
    }

However, from examples it seems the only way to do this is to implement the Validatable interface for all structs you want to check. The above code excerpt will not return an error because Foo does not implement the Validatable interface.

Is there any "default" way, like the one linked above, which will be able to iterate over each field and check if the fields are non-empty? Otherwise it seems if new fields are added, the validator method(s) needs to be updated.

swithek commented 1 year ago

At the moment, there are no default rules when validating structs. I'm also not sure whether that would be a good idea, since different projects, maybe even nested struct layers, might need different default rules. I would say that it should be up to you to update the validation methods when your structs change.