kvalid

package module
v1.0.8 Latest Latest
Warning

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

Go to latest
Published: Sep 20, 2023 License: MIT Imports: 8 Imported by: 1

README ΒΆ

kvalid

Action Report Card codecov godoc License

✨ xuender/kvalid is a lightweight validation library that can export rules as JSON so browsers can apply the same rules.

Based on Go 1.18+ Generics.

Learn from github.com/AgentCosmic/xvalid .

πŸ’‘ Usage

Define rules:

import (
  "fmt"
  "net/http"

  "github.com/xuender/kvalid"
  "github.com/xuender/kvalid/json"
)

type Book struct {
  Title  string `json:"title"`
  Author string `json:"author,omitempty"`
  Amount float64
  Num    int
}

// nolint: gomnd
func (p *Book) Validation(method string) *kvalid.Rules[*Book] {
  switch method {
  case http.MethodPut:
    return kvalid.New(p).
      Field(&p.Amount,
        kvalid.Required().SetMessage("amount required"),
        kvalid.MinNum(10.3).Optional().SetMessage("amount min 10.3"),
        kvalid.MaxNum(2000.0).SetMessage("amount max 2000"),
      ).
      Field(&p.Num, kvalid.Ignore())
  case http.MethodPost:
    return kvalid.New(p).
      Field(&p.Title,
        kvalid.Required().SetMessage("title required"),
        kvalid.MaxStr(200).SetMessage("title max 200"),
      ).
      Field(&p.Author,
        kvalid.Required().SetMessage("author required"),
        kvalid.MaxStr(100).SetMessage("author max 100"),
      )
  default:
    panic("illegal method:" + method)
  }
}

func (p *Book) Validate(method string) error {
  return p.Validation(method).Validate(p)
}

Validate object:

book := &Book{}
fmt.Println(book.Validate(http.MethodPost))

Export rules as JSON:

data, _ := json.Marshal(book.Validation(http.MethodPut))
fmt.Println(string(data))

Bind object:

source := &Book{Amount: 99.9, Num: 3}
target := &Book{}
rules := source.Validation(http.MethodPut)

rules.Bind(source, target)

πŸ”οΈ Validators

  • MaxNum, MinNum
    • int, int8, int16, int32, int64
    • uint, uint8, uint16, uint32, uint64
    • float32, float64
    • byte, rune
  • MaxStr, MinStr
  • MaxNullInt, MinNullInt
  • Required
  • Pattern
  • Email, URL
  • FieldFunc, StructFunc, Ignore

πŸ“Š Graphs

Graphs

πŸ‘€ Contributors

Contributors

πŸ“ License

Β© ender, 2023~time.Now

MIT LICENSE

Documentation ΒΆ

Overview ΒΆ

Package kvalid is lightweight validation library, based on Go 1.18+ Generics.

Index ΒΆ

Examples ΒΆ

Constants ΒΆ

This section is empty.

Variables ΒΆ

View Source
var (
	ErrStructNotPointer = errors.New("struct is not pointer")
	ErrIsNil            = errors.New("struct is nil")
	ErrFieldNotPointer  = errors.New("field is not pointer")
	ErrFindField        = errors.New("can't find field")
	ErrMissValidate     = errors.New("miss Validate func")
)

Functions ΒΆ

func IsEmail ΒΆ

func IsEmail(email string) bool

IsEmail returns true if the string is an email.

Example ΒΆ
package main

import (
	"fmt"

	"github.com/xuender/kvalid"
)

func main() {
	fmt.Println(kvalid.IsEmail("test@example.com"))
	fmt.Println(kvalid.IsEmail("test"))

}
Output:

true
false

func IsURL ΒΆ added in v1.0.7

func IsURL(url string) bool

IsURL returns true if the string is an URL.

Example ΒΆ
package main

import (
	"fmt"

	"github.com/xuender/kvalid"
)

func main() {
	fmt.Println(kvalid.IsURL("http//:example.com"))
	fmt.Println(kvalid.IsURL("http://www.example.com"))
	fmt.Println(kvalid.IsURL("ftp://aa:pp@www.example.com"))
	fmt.Println(kvalid.IsURL("http://localhost:4200"))
	fmt.Println(kvalid.IsURL("http://127.0.0.1:4200"))

}
Output:

false
true
true
true
true

Types ΒΆ

type EmailValidator ΒΆ

type EmailValidator struct {
	PatternValidator
}

EmailValidator field must be a valid email address.

func Email ΒΆ

func Email() *EmailValidator

Email field must be a valid email address.

func (*EmailValidator) MarshalJSON ΒΆ

func (p *EmailValidator) MarshalJSON() ([]byte, error)

MarshalJSON for this validator.

type Error ΒΆ

type Error interface {
	Error() string
	Field() string
}

Error when a rule is broken.

func NewError ΒΆ

func NewError(message, fieldName string) Error

NewError creates new validation error.

type Errors ΒΆ

type Errors []Error

Errors is a list of Error.

func (Errors) Error ΒΆ

func (p Errors) Error() string

Error will combine all errors into a list of sentences.

type FieldFuncValidator ΒΆ

type FieldFuncValidator[T any] struct {
	// contains filtered or unexported fields
}

FieldFuncValidator for validating with custom function.

func (*FieldFuncValidator[T]) HTMLCompatible ΒΆ

func (p *FieldFuncValidator[T]) HTMLCompatible() bool

HTMLCompatible for this validator.

func (*FieldFuncValidator[T]) Name ΒΆ

func (p *FieldFuncValidator[T]) Name() string

Name of the field.

func (*FieldFuncValidator[T]) SetMessage ΒΆ

func (p *FieldFuncValidator[T]) SetMessage(_ string) Validator

SetMessage set error message.

func (*FieldFuncValidator[T]) SetName ΒΆ

func (p *FieldFuncValidator[T]) SetName(name string)

SetName of the field.

func (*FieldFuncValidator[T]) Validate ΒΆ

func (p *FieldFuncValidator[T]) Validate(value T) Error

Validate the value.

type IgnoreValidator ΒΆ added in v1.0.5

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

IgnoreValidator only for bind.

func Ignore ΒΆ added in v1.0.5

func Ignore() *IgnoreValidator

Ignore only for bind.

func (*IgnoreValidator) HTMLCompatible ΒΆ added in v1.0.5

func (p *IgnoreValidator) HTMLCompatible() bool

HTMLCompatible for this validator.

func (*IgnoreValidator) Name ΒΆ added in v1.0.5

func (p *IgnoreValidator) Name() string

Name of the field.

func (*IgnoreValidator) SetMessage ΒΆ added in v1.0.5

func (p *IgnoreValidator) SetMessage(_ string) Validator

SetMessage set error message.

func (*IgnoreValidator) SetName ΒΆ added in v1.0.5

func (p *IgnoreValidator) SetName(name string)

SetName of the field.

func (*IgnoreValidator) Validate ΒΆ added in v1.0.5

func (p *IgnoreValidator) Validate(_ any)

Validate the value.

type MaxNullIntValidator ΒΆ

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

MaxNullIntValidator field have minimum value.

func MaxNullInt ΒΆ

func MaxNullInt(max int64) *MaxNullIntValidator

MaxNullInt field have minimum value.

func (*MaxNullIntValidator) HTMLCompatible ΒΆ

func (p *MaxNullIntValidator) HTMLCompatible() bool

HTMLCompatible for this validator.

func (*MaxNullIntValidator) MarshalJSON ΒΆ

func (p *MaxNullIntValidator) MarshalJSON() ([]byte, error)

MarshalJSON for this validator.

func (*MaxNullIntValidator) Name ΒΆ

func (p *MaxNullIntValidator) Name() string

Name of the field.

func (*MaxNullIntValidator) SetMessage ΒΆ

func (p *MaxNullIntValidator) SetMessage(msg string) Validator

SetMessage set error message.

func (*MaxNullIntValidator) SetName ΒΆ

func (p *MaxNullIntValidator) SetName(name string)

SetName of the field.

func (*MaxNullIntValidator) Validate ΒΆ

func (p *MaxNullIntValidator) Validate(value null.Int) Error

Validate the value.

type MaxNumValidator ΒΆ

type MaxNumValidator[N Number] struct {
	// contains filtered or unexported fields
}

MaxNumValidator field have maximum value.

func MaxNum ΒΆ

func MaxNum[N Number](max N) *MaxNumValidator[N]

MaxNum field have maximum value.

func (*MaxNumValidator[N]) HTMLCompatible ΒΆ

func (p *MaxNumValidator[N]) HTMLCompatible() bool

HTMLCompatible for this validator.

func (*MaxNumValidator[N]) MarshalJSON ΒΆ

func (p *MaxNumValidator[N]) MarshalJSON() ([]byte, error)

MarshalJSON for this validator.

func (*MaxNumValidator[N]) Name ΒΆ

func (p *MaxNumValidator[N]) Name() string

Name of the field.

func (*MaxNumValidator[N]) SetMessage ΒΆ

func (p *MaxNumValidator[N]) SetMessage(msg string) Validator

SetMessage set error message.

func (*MaxNumValidator[N]) SetName ΒΆ

func (p *MaxNumValidator[N]) SetName(name string)

SetName of the field.

func (*MaxNumValidator[N]) Validate ΒΆ

func (p *MaxNumValidator[N]) Validate(value N) Error

Validate the value.

type MaxStrValidator ΒΆ

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

MaxStrValidator field have maximum length.

func MaxStr ΒΆ

func MaxStr(max int) *MaxStrValidator

MaxStr field have maximum length.

func (*MaxStrValidator) HTMLCompatible ΒΆ

func (p *MaxStrValidator) HTMLCompatible() bool

HTMLCompatible for this validator.

func (*MaxStrValidator) MarshalJSON ΒΆ

func (p *MaxStrValidator) MarshalJSON() ([]byte, error)

MarshalJSON for this validator.

func (*MaxStrValidator) Name ΒΆ

func (p *MaxStrValidator) Name() string

Name of the field.

func (*MaxStrValidator) SetMessage ΒΆ

func (p *MaxStrValidator) SetMessage(msg string) Validator

SetMessage set error message.

func (*MaxStrValidator) SetName ΒΆ

func (p *MaxStrValidator) SetName(name string)

SetName of the field.

func (*MaxStrValidator) Validate ΒΆ

func (p *MaxStrValidator) Validate(value string) Error

Validate the value.

type MinNullIntValidator ΒΆ

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

MinNullIntValidator field have minimum value.

func MinNullInt ΒΆ

func MinNullInt(min int64) *MinNullIntValidator

MinNullInt field have minimum value.

func (*MinNullIntValidator) HTMLCompatible ΒΆ

func (p *MinNullIntValidator) HTMLCompatible() bool

HTMLCompatible for this validator.

func (*MinNullIntValidator) MarshalJSON ΒΆ

func (p *MinNullIntValidator) MarshalJSON() ([]byte, error)

MarshalJSON for this validator.

func (*MinNullIntValidator) Name ΒΆ

func (p *MinNullIntValidator) Name() string

Name of the field.

func (*MinNullIntValidator) Optional ΒΆ

func (p *MinNullIntValidator) Optional() Validator

Optional don't validate if the value is zero.

func (*MinNullIntValidator) SetMessage ΒΆ

func (p *MinNullIntValidator) SetMessage(msg string) Validator

SetMessage set error message.

func (*MinNullIntValidator) SetName ΒΆ

func (p *MinNullIntValidator) SetName(name string)

SetName of the field.

func (*MinNullIntValidator) Validate ΒΆ

func (p *MinNullIntValidator) Validate(value null.Int) Error

Validate the value.

type MinNumValidator ΒΆ

type MinNumValidator[N Number] struct {
	// contains filtered or unexported fields
}

MinNumValidator field have minimum value.

func MinNum ΒΆ

func MinNum[N Number](min N) *MinNumValidator[N]

MinNum field have minimum value.

func (*MinNumValidator[N]) HTMLCompatible ΒΆ

func (p *MinNumValidator[N]) HTMLCompatible() bool

HTMLCompatible for this validator.

func (*MinNumValidator[N]) MarshalJSON ΒΆ

func (p *MinNumValidator[N]) MarshalJSON() ([]byte, error)

MarshalJSON for this validator.

func (*MinNumValidator[N]) Name ΒΆ

func (p *MinNumValidator[N]) Name() string

Name of the field.

func (*MinNumValidator[N]) Optional ΒΆ

func (p *MinNumValidator[N]) Optional() Validator

Optional don't validate if the value is zero.

func (*MinNumValidator[N]) SetMessage ΒΆ

func (p *MinNumValidator[N]) SetMessage(msg string) Validator

SetMessage set error message.

func (*MinNumValidator[N]) SetName ΒΆ

func (p *MinNumValidator[N]) SetName(name string)

SetName of the field.

func (*MinNumValidator[N]) Validate ΒΆ

func (p *MinNumValidator[N]) Validate(value N) Error

Validate the value.

type MinStrValidator ΒΆ

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

MinStrValidator field must have minimum length.

func MinStr ΒΆ

func MinStr(min int) *MinStrValidator

MinStr field must have minimum length.

func (*MinStrValidator) HTMLCompatible ΒΆ

func (p *MinStrValidator) HTMLCompatible() bool

HTMLCompatible for this validator.

func (*MinStrValidator) MarshalJSON ΒΆ

func (p *MinStrValidator) MarshalJSON() ([]byte, error)

MarshalJSON for this validator.

func (*MinStrValidator) Name ΒΆ

func (p *MinStrValidator) Name() string

Name of the field.

func (*MinStrValidator) Optional ΒΆ

func (p *MinStrValidator) Optional() Validator

Optional don't validate if the value is zero.

func (*MinStrValidator) SetMessage ΒΆ

func (p *MinStrValidator) SetMessage(msg string) Validator

SetMessage set error message.

func (*MinStrValidator) SetName ΒΆ

func (p *MinStrValidator) SetName(name string)

SetName of the field.

func (*MinStrValidator) Validate ΒΆ

func (p *MinStrValidator) Validate(value string) Error

Validate the value.

type Number ΒΆ

type Number interface {
	constraints.Integer | constraints.Float
}

type PatternValidator ΒΆ

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

PatternValidator field must match regexp.

func Pattern ΒΆ

func Pattern(pattern string) *PatternValidator

Pattern field must match regexp.

func (*PatternValidator) HTMLCompatible ΒΆ

func (p *PatternValidator) HTMLCompatible() bool

HTMLCompatible for this validator.

func (*PatternValidator) MarshalJSON ΒΆ

func (p *PatternValidator) MarshalJSON() ([]byte, error)

MarshalJSON for this validator.

func (*PatternValidator) Name ΒΆ

func (p *PatternValidator) Name() string

Name of the field.

func (*PatternValidator) Optional ΒΆ

func (p *PatternValidator) Optional() Validator

Optional don't validate if the value is zero.

func (*PatternValidator) SetMessage ΒΆ

func (p *PatternValidator) SetMessage(msg string) Validator

SetMessage set error message.

func (*PatternValidator) SetName ΒΆ

func (p *PatternValidator) SetName(name string)

SetName of the field.

func (*PatternValidator) Validate ΒΆ

func (p *PatternValidator) Validate(value string) Error

Validate the value.

type RequiredValidator ΒΆ

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

RequiredValidator field must not be zero.

func Required ΒΆ

func Required() *RequiredValidator

Required fields must not be zero.

func (*RequiredValidator) HTMLCompatible ΒΆ

func (p *RequiredValidator) HTMLCompatible() bool

HTMLCompatible for this validator.

func (*RequiredValidator) MarshalJSON ΒΆ

func (p *RequiredValidator) MarshalJSON() ([]byte, error)

MarshalJSON for this validator.

func (*RequiredValidator) Name ΒΆ

func (p *RequiredValidator) Name() string

Name of the field.

func (*RequiredValidator) SetMessage ΒΆ

func (p *RequiredValidator) SetMessage(msg string) Validator

SetMessage set error message.

func (*RequiredValidator) SetName ΒΆ

func (p *RequiredValidator) SetName(name string)

SetName of the field.

func (*RequiredValidator) Validate ΒΆ

func (p *RequiredValidator) Validate(value any) Error

Validate the value.

type RuleHolder ΒΆ added in v1.0.2

type RuleHolder[T any] interface {
	Validation(string) *Rules[T]
	Validate(string) error
}

RuleHolder needs to be Rules.

type Rules ΒΆ

type Rules[T any] struct {
	// contains filtered or unexported fields
}

Rules for creating a chain of rules for validating a struct.

func New ΒΆ

func New[T any](structPtr T) *Rules[T]

New rule chain.

func (*Rules[T]) Bind ΒΆ added in v1.0.1

func (p *Rules[T]) Bind(source, target T) error
Example ΒΆ
package main

import (
	"fmt"
	"net/http"

	"github.com/xuender/kvalid"
)

type Book struct {
	Title  string `json:"title"`
	Author string `json:"author,omitempty"`
	Amount float64
	Num    int
}

// nolint: gomnd
func (p *Book) Validation(method string) *kvalid.Rules[*Book] {
	switch method {
	case http.MethodPut:
		return kvalid.New(p).
			Field(&p.Amount,
				kvalid.Required().SetMessage("amount required"),
				kvalid.MinNum(10.3).Optional().SetMessage("amount min 10.3"),
				kvalid.MaxNum(2000.0).SetMessage("amount max 2000"),
			).
			Field(&p.Num, kvalid.Ignore())
	case http.MethodPost:
		return kvalid.New(p).
			Field(&p.Title,
				kvalid.Required().SetMessage("title required"),
				kvalid.MaxStr(200).SetMessage("title max 200"),
			).
			Field(&p.Author,
				kvalid.Required().SetMessage("author required"),
				kvalid.MaxStr(100).SetMessage("author max 100"),
			)
	default:
		panic("illegal method:" + method)
	}
}

func (p *Book) Validate(method string) error {
	return p.Validation(method).Validate(p)
}

func main() {
	source := &Book{Title: "Hello World", Amount: 99.9, Num: 3}
	target := &Book{}
	postRules := source.Validation(http.MethodPost)
	putRules := source.Validation(http.MethodPut)

	fmt.Println(postRules.Bind(source, target))

	source.Author = "ender"
	fmt.Println(postRules.Bind(source, target))
	fmt.Println(target.Title)
	fmt.Println(target.Amount)

	fmt.Println(putRules.Bind(source, target))
	fmt.Println(target.Amount)
	fmt.Println(target.Num)

}
Output:

author required.
<nil>
Hello World
0
<nil>
99.9
3

func (*Rules[T]) Field ΒΆ

func (p *Rules[T]) Field(fieldPtr any, validators ...Validator) *Rules[T]

Field adds validators for a field.

func (*Rules[T]) MarshalJSON ΒΆ

func (p *Rules[T]) MarshalJSON() ([]byte, error)

func (*Rules[T]) OnlyFor ΒΆ

func (p *Rules[T]) OnlyFor(name string) *Rules[T]

OnlyFor filters the validators to match only the fields.

func (*Rules[T]) Struct ΒΆ

func (p *Rules[T]) Struct(validators ...Validator) *Rules[T]

Struct adds validators for the struct.

func (*Rules[T]) Validate ΒΆ

func (p *Rules[T]) Validate(subject T) error

Validate a struct and return Errors.

Example ΒΆ

nolint: lll

package main

import (
	"encoding/json"
	"fmt"
	"net/http"

	"github.com/xuender/kvalid"
)

type Book struct {
	Title  string `json:"title"`
	Author string `json:"author,omitempty"`
	Amount float64
	Num    int
}

// nolint: gomnd
func (p *Book) Validation(method string) *kvalid.Rules[*Book] {
	switch method {
	case http.MethodPut:
		return kvalid.New(p).
			Field(&p.Amount,
				kvalid.Required().SetMessage("amount required"),
				kvalid.MinNum(10.3).Optional().SetMessage("amount min 10.3"),
				kvalid.MaxNum(2000.0).SetMessage("amount max 2000"),
			).
			Field(&p.Num, kvalid.Ignore())
	case http.MethodPost:
		return kvalid.New(p).
			Field(&p.Title,
				kvalid.Required().SetMessage("title required"),
				kvalid.MaxStr(200).SetMessage("title max 200"),
			).
			Field(&p.Author,
				kvalid.Required().SetMessage("author required"),
				kvalid.MaxStr(100).SetMessage("author max 100"),
			)
	default:
		panic("illegal method:" + method)
	}
}

func (p *Book) Validate(method string) error {
	return p.Validation(method).Validate(p)
}

func main() {
	book := &Book{}
	fmt.Println(book.Validate(http.MethodPost))

	book.Title = "Hello World"
	fmt.Println(book.Validate(http.MethodPost))

	book.Author = "ender"
	fmt.Println(book.Validate(http.MethodPost))
	fmt.Println(book.Validate(http.MethodPut))

	data, _ := json.Marshal(book.Validation(http.MethodPut))
	fmt.Println(string(data))

}
Output:

	title required. author required.
author required.
<nil>
amount required.
{"Amount":[{"rule":"required","msg":"amount required"},{"rule":"minNum","min":10.3,"msg":"amount min 10.3"},{"rule":"maxNum","max":2000,"msg":"amount max 2000"}]}

func (*Rules[T]) Validators ΒΆ

func (p *Rules[T]) Validators() []Validator

Validators for this chain.

type StructFuncValidator ΒΆ

type StructFuncValidator[T any] struct {
	// contains filtered or unexported fields
}

StructFuncValidator validate struct with custom function.

func (*StructFuncValidator[T]) HTMLCompatible ΒΆ

func (c *StructFuncValidator[T]) HTMLCompatible() bool

HTMLCompatible for this validator.

func (*StructFuncValidator[T]) Name ΒΆ

func (c *StructFuncValidator[T]) Name() string

Name of the field.

func (*StructFuncValidator[T]) SetMessage ΒΆ

func (c *StructFuncValidator[T]) SetMessage(_ string) Validator

SetMessage set error message.

func (*StructFuncValidator[T]) SetName ΒΆ

func (c *StructFuncValidator[T]) SetName(name string)

SetName of the field.

func (*StructFuncValidator[T]) Validate ΒΆ

func (c *StructFuncValidator[T]) Validate(value T) Error

Validate the value.

type URLValidator ΒΆ added in v1.0.7

type URLValidator struct {
	PatternValidator
}

URLValidator field must be a valid URL.

func URL ΒΆ added in v1.0.7

func URL() *URLValidator

URL field must be a valid URL.

func (*URLValidator) MarshalJSON ΒΆ added in v1.0.7

func (p *URLValidator) MarshalJSON() ([]byte, error)

MarshalJSON for this validator.

type ValidJSONer ΒΆ added in v1.0.4

type ValidJSONer interface {
	ValidJSON() map[string]json.Marshaler
}

ValidJSONer to implement a Validator JSON map.

type Validator ΒΆ

type Validator interface {
	SetName(string)
	Name() string
	HTMLCompatible() bool
	SetMessage(string) Validator
}

Validator to implement a rule.

func FieldFunc ΒΆ

func FieldFunc[T any](checker func(string, T) Error) Validator

FieldFunc for validating with custom function.

func StructFunc ΒΆ

func StructFunc[T any](checker func(T) Error) Validator

StructFunc validate struct with custom function.

Jump to

Keyboard shortcuts

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