Skip to content
go validation library
Branch: master
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
example
.gitignore
LICENSE
README.md
builtins.go
builtins_test.go
common.go
common_test.go
doc.go
e2e_test.go
errors.go
errors_test.go
object.go
object_test.go
slice.go
slice_test.go
util.go
values.go
values_test.go

README.md

Valval Build Status Coverage Status GoDoc

Valval is simple validation library for Go.

Defines a validator

personValidator := valval.Object(valval.M{
	"Name": valval.String(
		valval.MaxLength(20),
		valval.Regexp(regexp.MustCompile(`^[a-z ]+$`)),
	),
	"Attr": valval.Object(valval.M{
		"Age": valval.Number(
			valval.Min(0),
			valval.Max(120),
		),
		"Gender": valval.String(valval.In("male", "female")),
		"Tags": valval.Slice(
			valval.String(
				valval.MinLength(1),
				valval.MaxLength(10),
			),
		).Self(valval.MaxSliceLength(10)),
	}),
})

validate a struct

type PersonAttr struct {
	Age    int
	Gender string
	Tags   []string
}
type Person struct {
	Name string
	Attr PersonAttr
}
person := &Person{
	Name: "John!",
	Attr: PersonAttr{
		Age:    200,
		Gender: "otoko",
		Tags:   []string{"", "abcdefghijklmn"},
	},
}
if err := personValidator.Validate(person); err != nil {
	errs := valval.Errors(err)
	for _, errInfo := range errs {
		fmt.Printf("%s : %v\n", errInfo.Path, errInfo.Error)
	}
}
/* outputs
Attr.Age : must be 200 or less
Attr.Gender : invalid value. allowed are [male female]
Attr.Tags[0] : length must be 1 or greater
Attr.Tags[1] : length must be 10 or less
Name : must be match to the regexp ^[a-z ]+$
*/

and validate a map

personMap := map[string]interface{}{
	"Name": "John!",
	"Attr": map[string]interface{}{
		"Age":    200,
		"Gender": "otoko",
		"Tags":   []string{"", "abcdefghijklmn"},
	},
}
if err := personValidator.Validate(personMap); err != nil {
	errs := valval.Errors(err)
	for _, errInfo := range errs {
		fmt.Printf("%s : %v\n", errInfo.Path, errInfo.Error)
	}
}
// outputs same as struct

Install

go get github.com/wcl48/valval
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.