Tavern 台灣正體
Tavern is a struct-tag free validation library with custom validator supported.
Tired of all the form validation that based on the struct tags. With Tavern you can validate the values without a struct.
$ go get github.com/teacat/tavern
err := tavern.Validate(
NewRule("Hello, world!",
tavern.WithRequired(),
tavern.WithMinLength(5),
),
NewRule(198964,
tavern.WithMin(100),
),
)
if err != nil {
panic(err)
}
A validation contains the rules, and a rule requires a value and the validators. Validators can be chained and communicate by passing the context.
Here are the few built-in validators: WithRequired
, WithLength
, WithRange
, etc. Check GoDoc to see more built-in validators.
It's possible to create your own validators.
type Validator func(ctx context.Context, value interface{}) (context.Context, error)
The context argument can be used as a communication between the validators, with ctx.Value(tavern.KeyRequired).(bool)
you are able to get a boolean that states the value is required or not.
By default, Tavern returns built-in errors such as ErrRequired
, ErrLength
might not be what you wanted. You are able to create your own custom error for each validator by using WithCustomError(validator Validator, err error)
function.
It's also a validator but returns your own custom error when the passed-in validator failed.
err := tavern.Validate(
NewRule("",
tavern.WithCustomError(tavern.WithRequired(), errors.New("nani the fuck")),
tavern.WithMinLength(5),
),
)
if err != nil {
panic(err) // output: nani the fuck
}
WithIPv4Address
allows::0
which is IPv6.WithIPAddress
,WithIPv4Address
,WithIPv6Address
allows IP with port numbers.
IPAddress validators use net.ResolveIPAddr
as validation, not sure why it is valid.