Skip to content
/ valis Public

valis is a validation framework for Go.

License

Notifications You must be signed in to change notification settings

soranoba/valis

Repository files navigation

valis

CircleCI Go Report Card PkgGoDev

Valis is a validation framework for Go.

Overviews

  • 👌 Validation in various ways
    • struct tag, Validate methods, and various other ways.
  • 🔧 Excellent customizability.
  • 🌎 Support translations.

Motivations

Validation in various ways

go-playground/validator is a great validation framework, but it only supports the way using struct tag.
go-ozzo/ozzo-validation supports the way using Validate methods, but it does not have enough features to use struct tag.
Valis supports to validate in various ways due to its excellent extensibility.

Create validation rules from multiple struct tags

When using various libraries, it is often the case that constraints with the same content are described by other struct tags.
For example, required:"true" validate:"required".

What this !?!?
Can you guarantee that both are always in agreement?

Valis solves this by supporting to read all tags.

Customizability is power

Performance is important, but it's faster not to use the library.
Therefore, Valis take emphasis on customizability.

So, requests for customizability are also welcomed.

Installation

To install it, run:

go get -u github.com/soranoba/valis

Usage

Basic

package main

import (
	"fmt"
	"github.com/soranoba/valis"
	"github.com/soranoba/valis/is"
)

func main() {
	type User struct {
		Name string
		Age  int
	}

	u := &User{}
	if err := valis.Validate(
		&u,
		valis.Field(&u.Name, is.NonZero),
		valis.Field(&u.Age, is.Min(20)),
	); err != nil {
		fmt.Println(err)
	}
}

Struct tag

package main

import (
	"fmt"
	"github.com/soranoba/valis"
	"github.com/soranoba/valis/tagrule"
	"github.com/soranoba/valis/when"
)

func main() {
	type User struct {
		Name    *string `required:"true"`
		Age     int     `validate:"min=20"`
		Company struct {
			Location *string `required:"true"`
		}
	}

	v := valis.NewValidator()
	// Use the CommonRule if you want to automatically search and validate all hierarchies.
	v.SetCommonRules(
		when.IsStruct(valis.EachFields(tagrule.Required, tagrule.Validate)).
			ElseWhen(when.IsSliceOrArray(valis.Each( /* only common rules */ ))).
			ElseWhen(when.IsMap(valis.EachValues( /* only common rules */ ))),
	)

	user := User{}
	if err := v.Validate(&user); err != nil {
		fmt.Println(err)
	}
}

Please refer to documents for other usages.

About

valis is a validation framework for Go.

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages