Skip to content
This repository was archived by the owner on Nov 27, 2023. It is now read-only.

teacat/tavern

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

35 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Tavern 台灣正體 GoDoc Coverage Status Build Status Go Report Card

Tavern is a struct-tag free validation library with custom validator supported.

Why?

Tired of all the form validation that based on the struct tags. With Tavern you can validate the values without a struct.

Installation

$ go get github.com/teacat/tavern

Example

err := tavern.Validate(
    NewRule("Hello, world!",
        tavern.WithRequired(),
        tavern.WithMinLength(5),
    ),
    NewRule(198964,
        tavern.WithMin(100),
    ),
)
if err != nil {
    panic(err)
}

Validators

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.

Custom 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.

Custom Errors

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
}

Known Bugs

  • 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.

About

✔️ Form validation without struct tags

Topics

Resources

License

Stars

Watchers

Forks

Languages