Skip to content

disgoorg/validate

Repository files navigation

Go Reference Go Report Go Version License DisGo Version DisGo Discord

validate

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.

Getting Started

Installing

$ go get github.com/disgoorg/validate

Usage

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)
    }
}

Custom Validators

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

Documentation can be found here

  • Go Reference

Examples

You can find examples here

Troubleshooting

For help feel free to open an issue or reach out on Discord

Contributing

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.

License

Distributed under the License. See LICENSE for more information.

Releases

No releases published

Languages