govalid

package module
v1.3.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 14, 2021 License: MIT Imports: 8 Imported by: 1

README

Govalid

Use Govalid to validate structs.

Documentation

For full documentation see pkg.go.dev.

Example

package main

import (
	"fmt"
	"log"
	"strings"

	"github.com/twharmon/govalid"
)

type Post struct {
	// ID has no constraints
	ID int

	// Title is required, must be at least 3 characters long, cannot be
	// more than 20 characters long, and must match ^[a-zA-Z ]+$
	Title string `govalid:"req|min:3|max:20|regex:^[a-zA-Z ]+$"`

	// Body is not required, cannot be more than 10000 charachers,
	// and must be "fun" (a custom rule defined below).
	Body string `govalid:"max:10000|fun"`

	// Category is not required, but if not zero value ("") it must be
	// either "announcement" or "bookreview".
	Category string `govalid:"in:announcement,bookreview"`
}

var v = govalid.New()

func main() {
	// Add Custom validation to the struct `Post`
	v.AddCustom(Post{}, func(val interface{}) string {
		post := val.(*Post)
		if post.Category != "" && !strings.Contains(post.Body, post.Category) {
			return fmt.Sprintf("Body must contain %s", post.Category)
		}
		return ""
	})
	
	// Add custom string "fun" that can be used on any string field
	// in any struct.
	v.AddCustomStringRule("fun", func(field string, value string) string {
		if float64(strings.Count(value, "!")) / float64(utf8.RuneCountInString(value)) > 0.001 {
			return ""
		}
		return fmt.Sprintf("%s must contain more exclamation marks", field)
	})

	p := Post{
		ID:       5,
		Title:    "Hi",
		Body:     "Hello world!",
		Category: "announcement",
	}

	vio, err := v.Violations(&p)
	if err != nil {
		log.Fatalln(err)
	}

	fmt.Println(vio)
}

Benchmarks

BenchmarkValidatorStringReqInvalid	         267.3 ns/op	  48 B/op	       3 allocs/op
BenchmarkValidatorStringReqValid	        92.35 ns/op	      16 B/op	       1 allocs/op
BenchmarkValidatorsVariety	                1484 ns/op	     297 B/op	      15 allocs/op

Contribute

Make a pull request.

Documentation

Index

Examples

Constants

This section is empty.

Variables

View Source
var ErrNotRegistered = errors.New("structs must be registered before validating")

Deprecated: ErrNotRegistered is deprecated.

View Source
var ErrNotStruct = errors.New("only structs can be validated")

ErrNotStruct is encountered when an attempt is made to validate a type that is not a struct is made.

Functions

This section is empty.

Types

type Validator

type Validator struct {
	// contains filtered or unexported fields
}

Validator .

func New

func New() *Validator

New .

func (*Validator) AddCustom

func (v *Validator) AddCustom(s interface{}, f ...func(interface{}) string) error

AddCustom adds custom validation functions to struct s.

func (*Validator) AddCustomFloat64Rule added in v1.2.0

func (v *Validator) AddCustomFloat64Rule(name string, validatorFunc func(string, float64) string)

AddCustomFloat64Rule adds custom validation tag for float64.

func (*Validator) AddCustomInt64Rule added in v1.2.0

func (v *Validator) AddCustomInt64Rule(name string, validatorFunc func(string, int64) string)

AddCustomInt64Rule adds custom validation tag for int64.

func (*Validator) AddCustomStringRule added in v1.2.0

func (v *Validator) AddCustomStringRule(name string, validatorFunc func(string, string) string)

AddCustomStringRule adds custom validation tag for string.

func (*Validator) Register deprecated

func (v *Validator) Register(structs ...interface{}) error

Deprecated: Register is deprecated. Structs are registered as needed.

func (*Validator) Violation

func (v *Validator) Violation(s interface{}) (string, error)

Violation checks the struct s against all constraints and custom validation functions, if any. It returns an violation if the struct fails validation. If the type being validated is not a struct, ErrNotStruct will be returned.

Example
package main

import (
	"fmt"

	"github.com/twharmon/govalid"
)

func main() {
	v := govalid.New()
	type User struct {
		Name string `govalid:"req|min:2|max:32"`
		Role string `govalid:"req|in:user,editor,admin"`
		Age  int    `govalid:"req|min:18"`
	}
	user := User{
		Name: "foo",
		Role: "super_admin",
		Age:  10,
	}
	vio, _ := v.Violation(&user)
	fmt.Println(vio)
}
Output:

Role must be in [user editor admin]

func (*Validator) Violations

func (v *Validator) Violations(s interface{}) ([]string, error)

Violations checks the struct s against all constraints and custom validation functions, if any. It returns a slice of violations if the struct fails validation. If the type being validated is not a struct, ErrNotStruct will be returned.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL