govalid

package module
v0.0.1 Latest Latest
Warning

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

Go to latest
Published: Feb 21, 2024 License: MIT Imports: 7 Imported by: 1

README

govalid

A simple Go struct validator.

Go Report Card

Quick Start

go get -u github.com/wuhan005/govalid

v := struct {
    Name string `valid:"required;username" label:"昵称"`
    ID   int    `valid:"required;min:0;max:999" label:"用户编号"`
    Mail string `valid:"required;email" label:""`
}{
    "e99_", 1990, "i@github.red.",
}

errs, ok := govalid.Check(v)
if !ok {
    for _, err := range errs {
        fmt.Println(err)
    }
}

Output:

昵称的最后一个字符不能为下划线
用户编号应小于999
不是合法的电子邮箱格式

Customize Error Message

govalid.SetMessageTemplates(map[string]string{
    "required": "can't be null.",
    "min": "must bigger than %v.",
})

Customize Error Check Function

func main() {
	// set your error message.
	govalid.SetMessageTemplates(map[string]string{
		"mycheck": "content cann't contain 'e99'.",
	})

	// add new check function
	govalid.Checkers["mycheck"] = func(c govalid.CheckerContext) *govalid.ErrContext {
		errCtx := govalid.NewErrorContext(c)
		value, ok := ctx.Value.(string)
		if !ok {
			return MakeCheckerParamError(c)
		}
		if strings.Contains(value, "e99") {
			return ctx
		}
		// if the check passed, return nil.
		return nil
	}

	r := struct {
		Content string `valid:"mycheck"`
	}{
		"helloe99",
	}

    errs, ok := govalid.Check(v)
    if !ok {
        for _, err := range errs {
            fmt.Println(err)
        }
    }
}

Special Thanks

https://github.com/jiazhoulvke/echo-form

LICENSE

MIT

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	FieldNamePlaceholder  = "{field}"
	FieldLimitPlaceholder = "{limit}"
)
View Source
var (
	// RulesField is the validation rules tag's name.
	RulesField = "valid"
	// LabelField is the field label tag's name.
	LabelField = "label"
	// MessageField is the error message tag's name.
	MessageField = "msg"
)
View Source
var Checkers = map[string]CheckFunc{
	"required":     required,
	"min":          min,
	"max":          max,
	"minlen":       minlen,
	"maxlen":       maxlen,
	"alpha":        alpha,
	"alphanumeric": alphaNumeric,
	"alphadash":    alphaDash,
	"username":     userName,
	"email":        email,
	"ipv4":         ipv4,
	"mobile":       mobile,
	"tel":          tel,
	"phone":        phone,
	"idcard":       idCard,
	"equal":        equal,
	"list":         list,
}

Checkers is the function list of checkers.

View Source
var MobilePattern = regexp.MustCompile(`^(?:\+?86)?1(?:3\d{3}|5[^4\D]\d{2}|8\d{3}|7(?:[0-35-9]\d{2}|4(?:0\d|1[0-2]|9\d))|9[0-35-9]\d{2}|6[2567]\d{2}|4(?:(?:10|4[01])\d{3}|[68]\d{4}|[579]\d{2}))\d{6}$`)

MobilePattern is used to check the mobile phone. Refer to https://github.com/VincentSit/ChinaMobilePhoneNumberRegex

Functions

This section is empty.

Types

type CheckFunc

type CheckFunc func(ctx CheckerContext) *ErrContext

CheckFunc is the type of checker function. It returns an error context if error occurred.

type CheckerContext

type CheckerContext struct {
	StructValue      reflect.Value
	FieldName        string
	FieldType        reflect.Type
	FieldValue       interface{}
	FieldLabel       string
	TemplateLanguage language.Tag

	Rule *rule
}

CheckerContext is the context of checker, which can contains the rule of the checker and the value of the current struct field.

type ErrContext

type ErrContext struct {
	FieldName        string
	FieldLabel       string
	FieldValue       interface{}
	TemplateLanguage language.Tag
	// contains filtered or unexported fields
}

ErrContext contains the error context.

func Check

func Check(v interface{}, lang ...language.Tag) (errs []*ErrContext, ok bool)

Check checks the struct value.

func MakeCheckerNotFoundError

func MakeCheckerNotFoundError(c CheckerContext) *ErrContext

func MakeCheckerParamError

func MakeCheckerParamError(c CheckerContext) *ErrContext

func MakeFieldNotFoundError

func MakeFieldNotFoundError(c CheckerContext) *ErrContext

func MakeUserDefinedError

func MakeUserDefinedError(msg string) *ErrContext

func MakeValueTypeError

func MakeValueTypeError(c CheckerContext) *ErrContext

func NewErrorContext

func NewErrorContext(c CheckerContext) *ErrContext

NewErrorContext return a error context.

func (*ErrContext) Error

func (e *ErrContext) Error() string

func (*ErrContext) SetFieldLimitValue

func (e *ErrContext) SetFieldLimitValue(v interface{})

func (*ErrContext) SetTemplate

func (e *ErrContext) SetTemplate(key string)

Jump to

Keyboard shortcuts

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