Jim Myhrberg 9c3b63361d fix(validate): do not panic with field errors on non-struct types
When validating non-struct types, we should not try and convert field
values in errors, because there is no struct field to lookup. Hence this
fix stops a panic from happening.

It is up to the Validate() method itself to provide the correct and
final field value when validating non-struct types.
2021-08-23 12:55:24 +01:00
2021-08-22 22:18:01 +01:00
2021-08-22 21:53:02 +01:00
2021-08-22 21:53:02 +01:00
2021-08-22 22:10:33 +01:00

go-validate

Yet another Go struct/object validation package, with a focus on simplicity, flexibility, and full control over validation logic.

Go Reference GitHub tag (latest SemVer) Actions Status Coverage GitHub issues GitHub pull requests License Status

Add validation to any type, by simply implementing the Validatable interface:

type Validatable interface {
	Validate() error
}

Import

import "github.com/romdo/go-validate"

Example

type Order struct {
	Books []*Book `json:"books"`
}

type Book struct {
	Title  string `json:"title"`
	Author string `json:"author"`
}

func (s *Book) Validate() error {
	var errs error
	if s.Title == "" {
		errs = validate.Append(errs, &validate.Error{
			Field: "Title", Msg: "is required",
		})
	}

	// Helper to perform the same kind of check as above for Title.
	errs = validate.Append(errs, validate.RequireField("Author", s.Author))

	return errs
}

func main() {
	errs := validate.Validate(&Order{Books: []*Book{{Title: ""}}})

	for _, err := range validate.Errors(errs) {
		fmt.Println(err.Error())
	}
}

Above example produces the following output:

books.0.title: is required
books.0.author: is required

Documentation

Please see the Go Reference for documentation and examples.

LICENSE

MIT

Description
Yet another Go struct/object validation package, with a focus on simplicity, flexibility, and full control over validation logic.
Readme MIT 164 KiB
Languages
Go 94%
Makefile 6%