Validate is a simple type validation library built with Go 1.18 generics. It provides an alternative approach to using struct tags to validate structs or other types.
$ go get github.com/disgoorg/validate
Usage is simple. Create a new type and implement the validate.Validator
interface. Then, use the validate.Validate
function with validate.New
and pass the field or value to validate as first parameter.
After this you can pass as many validate.ValidateFunc[any]
functions as you want to validate the value. The functions will be executed in order and the first one that returns an error will stop the validation.
import "github.com/disgoorg/validate"
type Foo struct {
Bar string
Baz int
}
func (f Foo) Validate() error {
return validate.Validate(
validate.New(f.Bar, validate.Required[string], validate.StringRange(0, 10)),
validate.New(f.Baz, validate.Required[int], validate.NumberRange(-5, 5)),
)
}
func main() {
f := Foo{
Bar: "",
Baz: -1,
}
if err := f.Validate(); err != nil {
panic(err)
}
}
Validate comes with a few predefined validators, but you can also implement your own validators. For this you can use functions with closures to pass parameters to the validator func.
Here is an example:
func StringRange(min int, max int) ValidatorFunc[string] {
return func(v string) error {
if len(v) < min || len(v) > max {
return fmt.Errorf("string must be between %d and %d characters", min, max)
}
return nil
}
}
Documentation can be found here
You can find examples here
For help feel free to open an issue or reach out on Discord
Contributions are welcomed but for bigger changes we recommend first reaching out via Discord or create an issue to discuss your problems, intentions and ideas.