kvalid

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Aug 31, 2023 License: MIT Imports: 8 Imported by: 1

README

kvalid

Action Report Card godoc License

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

Support Go 1.18 and later.

Learn from github.com/AgentCosmic/xvalid .

Use

Define rules and validate objects and export rules as JSON:

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
}

// nolint: gomnd
func (p *Book) Validation(method string) *kvalid.Rules {
  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"),
      )
  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)
}

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

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

Validators

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

License

© ender, 2023~time.Now

MIT LICENSE

Documentation

Overview

Package kvalid is lightweight validation library, support Go 1.18 and later.

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.

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 (v 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(msg 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 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 Rules

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

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

func New

func New(structPtr any) *Rules

New rule chain.

func (*Rules) Field

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

Field adds validators for a field.

func (*Rules) MarshalJSON

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

func (*Rules) OnlyFor

func (p *Rules) OnlyFor(name string) *Rules

OnlyFor filters the validators to match only the fields.

func (*Rules) Struct

func (p *Rules) Struct(validators ...Validator) *Rules

Struct adds validators for the struct.

func (*Rules) Validate

func (p *Rules) Validate(subject any) error

Validate a struct and return Errors.

Example

nolint: lll

package main

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
}

// nolint: gomnd
func (p *Book) Validation(method string) *kvalid.Rules {
	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"),
			)
	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)
}

// nolint: lll
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) Validators

func (p *Rules) 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(msg 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 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.

Directories

Path Synopsis
Package json Marshals.
Package json Marshals.

Jump to

Keyboard shortcuts

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