xuender / kvalid

Lightweight validation library that can export rules as JSON so browsers can apply the same rules.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

kvalid

Action Report Card Codecov Lines of code 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

About

Lightweight validation library that can export rules as JSON so browsers can apply the same rules.

License:MIT License


Languages

Language:Go 99.1%Language:Makefile 0.9%