invopop / validation

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

Expand documentation #3

Closed codedge closed 1 year ago

codedge commented 1 year ago

Hey,

I struggeling with the section Maps/Slices/Arrays of Validatables as I cannot see where the rules are set.

addresses := []Address{
    Address{State: "MD", Zip: "12345"},
    Address{Street: "123 Main St", City: "Vienna", State: "VA", Zip: "12345"},
    Address{City: "Unknown", State: "NC", Zip: "123"},
}
err := validation.Validate(addresses)
fmt.Println(err)
// Output:
// 0: (City: cannot be blank; Street: cannot be blank.); 2: (Street: cannot be blank; Zip: must be in a valid format.).

In this example how do you pass the rule for the city field, f. ex. to validate required. Could you enrich this example with the rules that are indicated in the errors 0: (City: cannot be blank; Street: cannot be blank.); 2: (Street: cannot be blank; Zip: must be in a valid format.).?

Thanks!

samlown commented 1 year ago

Hi! So the key for this example is in the paragraph above that says:

When validating an iterable (map, slice, or array), whose element type implements the validation.Validatable interface, the validation.Validate method will call the Validate method of every non-nil element.

Basically what they're saying there is that Address struct has a Validate() error method implementation that will validate the struct. You can see the example for that here: https://github.com/invopop/validation#validating-a-struct

I hope that's clearer!