jellydator / validation

An idiomatic validation package. Supports configurable and extensible validation rules (validators) using normal language constructs instead of error-prone struct tags.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Possible to have "default validation" for structs?

PMcca opened this issue · comments

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.

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.