checker

package module
v0.0.0-...-f2dff0e Latest Latest
Warning

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

Go to latest
Published: Apr 17, 2021 License: MIT Imports: 10 Imported by: 0

README

Checker

Go Report Card GoDoc Go Reference Build Status License Coverage Status

中文版本

Checker is a parameter validation package, can be use in struct/non-struct validation, including cross field validation in struct, elements validation in Slice/Array/Map, and provides customized validation rule.

Requirements

Go 1.13 or above.

Installation

go get -u github.com/liangyaopei/checker

Usage

When use Add to add rule,fieldExpr has three situations:

  • fieldExpr is empty,validate the value directly.
  • fieldExpr is single field,fetch value in struct, then validate.
  • fieldExpr is string separated by ., fetch value in struct according hierarchy of struct, then validate.

When fetching value by fieldExpr, if the field is pointer, it will fetch the underlying value of pointer to validate; if the field is nil pointer, it failed validation rule.

For special use of validating nil pointer, Nil rule can be used.

example from checker_test.go

// Item.Email is the format of email address
type Item struct {
	Info  typeInfo
	Email string
}

type typeStr string
// Item.Info.Type = "range",typeInfo.Type 's length is 2,elements with format of "2006-01-02"
// Item.Info.Type = "last",typeInfo.Type 'is length is 1,elements is positive integer,Granularity is one of day/week/month
type typeInfo struct {
	Type        typeStr
	Range       []string
	Unit        string
	Granularity string
}


// rules are as follow
rule := And(
		Email("Email"),
		Field("Info",
			Or(
				And(
					EqStr("Type", "range"),
					Length("Range", 2, 2),
					Array("Range", isDatetime("", "2006-01-02")),
				),
				And(
					EqStr("Type", "last"),
					InStr("Granularity", "day", "week", "month"),
					Number("Unit"),
				),
			),
		),
	)
itemChecker := NewChecker()
// validate parameter
itemChecker.Add(rule, "wrong item")

rule variable in above code constructs a rule tree. rule tree

To Note that, different rule tree can produce same validation rule, above rule can be rewritten as

rule := And(
		Email("Email"),
		Or(
			And(
				EqStr("Info.Type", "range"),
				Length("Info.Range", 2, 2),
				Array("Info.Range", Time("", "2006-01-02")),
			),
			And(
				EqStr("Info.Type", "last"),
				InStr("Info.Granularity", "day", "week", "month"),
				Number("Info.Unit"),
			),
		),
	)

rule tree2

Although rule trees are different, fieldExpr of leaf nodes in trees are same, which can be used as cache, and the validation logic is same.

Rule

Rule is an interface, it has many implementations. Its implementations can be categorized into two kinds: composite rule and singleton rule.

Composite Rule

Composite Rule contains other rules.

Name Usage
Field(fieldExpr string, rule Rule) Rule Applies rule to validate fieldExpr
And(rules ...Rule) Rule It needs all rules pass
Or(rules ...Rule) Rule It needs any rule passed
Not(innerRule Rule) Rule opposite the rule
Array(fieldExpr string, innerRule Rule) Rule Applies rule to elements in array
Map(fieldExpr string, keyRule Rule, valueRule Rule) Rule Applies keyRule and valueRule to key and value in map
Singleton Rule

Singleton Rule can be categorized into comparison rule, enum rule and format rule.

Comparison Rule

Comparison Rule can be categorized into single field comparison rule and multi-field comparison rule

single field comparison rule includes:

Name
EqInt(filedExpr string, equivalent int) Rule
NeInt(filedExpr string, inequivalent int) Rule
RangeInt(filedExpr string, ge int, le int) Rule

It also has the implementation of uint, stringfloattime.Time , Comparable.

multi-field comparison rule includes

Name
CrossComparable(fieldExprLeft string, fieldExprRight string, op operand) Rule

fieldExprLeftfieldExprRight is to located the field involving comparsion, op is the operand.

CrossComparable supports int`uint\float\string\time.Time\Comparable`.

Enum Rule

Enum Rule includes

Name
InStr(filedExpr string, enum ...string) Rule
InInt(filedExpr string, enum ...int) Rule
InUint(filedExpr string, enum ...uint) Rule
InFloat(filedExpr string, enum ...float64) Rule
Format Rule

Format Rule includes

Name
Email(fieldExpr string) Rule
Number(fieldExpr string) Rule
URL(fieldExpr string) Rule
Ip(fieldExpr string) Rule

etc.

Customized Rule

In addition to above rules, user can pass validation function to Custome to achieve purpose of implementing customized rule, refer to example

Checker

Checekr is an interface

  • Add(rule Rule, prompt string). Add rule and error prompt of failing the rule.
  • Check(param interface{}) (bool, string, string). Validate a parameter. It returns if it passes the rule, error prompt and error message to tell which field doesn't pass which rule.

Error log And Customized Error Prompt

When defining rules, it can define the error prompt when rule failed.example

rule := checker.And(
		checker.Email("Email").Prompt("Wrong email format") // [1],
		checker.And(
			checker.EqStr("Info.Type", "range"),
			checker.Length("Info.Range", 2, 2).Prompt("Range's length should be 2") // [2],
			checker.Array("Info.Range", checker.Time("", "2006-01-02")).
				Prompt("Range's element should be time format") // [3],
		),
	)

	validator := checker.NewChecker()
	validator.Add(rule, "wrong parameter") // [4]
    isValid, prompt, errMsg := validator.Check(item)

When rule fails, checker tries to return the rule's prompt([1]/[2]/[3] in code). If rule doesn't have its prompt, checker returns the prompt when adding the rule([4] in code).

errMsg is error log, is used to locate the filed that fails, refer it to example

Field Cache

From above graphic representation of rule tree, it can be found that when leaf node with same field expression, its value can be cached to reduce the cost of reflection.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	CrossFieldEq = eqOperand{}
	CrossFieldNe = neOperand{}
	CrossFieldGt = gtOperand{}
	CrossFieldGe = geOperand{}
	CrossFieldLt = ltOperand{}
	CrossFieldLe = leOperand{}
)

cross field comparison operand variables

Functions

func Alpha

func Alpha(fieldExpr string) *regexRule

Alpha is the validation function for validating if the current field's value is a valid alpha value.

func AlphaNumeric

func AlphaNumeric(fieldExpr string) *regexRule

AlphaNumeric is the validation function for validating if the current field's value is a valid alphanumeric value.

func And

func And(rules ...Rule) *andRule

And accepts slice of rules It passed when all rules passed

func Array

func Array(fieldExpr string, innerRule Rule) *arrayRule

Array checks if the filed is slice/array and its elements satisfy the innerRule

func CrossComp

func CrossComp(fieldExprLeft string, fieldExprRight string, op operand) *crossFieldCompareRule

CrossComp checks if left and right fields are same types and satisfy the comparison operand

func Custom

func Custom(fieldExpr string, checkFn func(exprValue interface{}) (bool, string)) *customRule

func Dir

func Dir(fieldExpr string) *dirRule

Dir is the validation function for validating if the current field's value is a valid directory.

func Email

func Email(fieldExpr string) *regexRule

Email is the validation function for validating if the current field's value is a valid email address.

func EndsWith

func EndsWith(fieldExpr string, suffix string) *endsWithRule

EndsWith is the validation function for validating that the field's value ends with the text specified within the param.

func EqComp

func EqComp(filedExpr string, equivalent Comparable) *eqRuleComp

EqComp checks if the field is Comparable and is equal to given Comparable variable

func EqFloat

func EqFloat(filedExpr string, equivalent float64) *eqRuleFloat

EqFloat is the validation function for validating if the field's value is equal to given float.

func EqInt

func EqInt(filedExpr string, equivalent int) *eqRuleInt

EqInt is the validation function for validating if the field's value is equal to given int.

func EqStr

func EqStr(filedExpr string, equivalent string) *eqRuleString

EqStr is the validation function for validating if the field's value is equal to given string.

func EqTime

func EqTime(filedExpr string, equivalent time.Time) *eqRuleTime

EqTime is the validation function for validating if the field's value is equal to given timestamp.

func EqTimeStr

func EqTimeStr(filedExpr string, layout string, equivalent time.Time) *eqRuleTimeStr

EqTimeStr is the validation function for validating if the field's value string and is equal to given timestamp.

func EqUint

func EqUint(filedExpr string, equivalent uint) *eqRuleUint

EqUint is the validation function for validating if the field's value is equal to given uint.

func Field

func Field(fieldExpr string, subRule Rule) *fieldRule

Field applies rule to fieldExpr

func HTML

func HTML(fieldExpr string) *regexRule

HTML is the validation function for validating if the current field's value is a valid HTML.

func HTMLEncoded

func HTMLEncoded(fieldExpr string) *regexRule

HTMLEncoded is the validation function for validating if the current field's value is a valid encoded HTML.

func HostName

func HostName(fieldExpr string) *regexRule

HostName is the validation function for validating if the current field's value is a valid RFC953 hostname.

func IPv4

func IPv4(fieldExpr string) *ipv4Rule

IPv4 is the validation function for validating if a value is a valid v4 IP address.

func IPv6

func IPv6(fieldExpr string) *ipv6Rule

IPv6 is the validation function for validating if the field's value is a valid v6 IP address.

func ISBN

func ISBN(fieldExpr string) *iSBNRule

ISBN is the validation function for validating if the field's value is a valid v10 or v13 ISBN.

func ISBN10

func ISBN10(fieldExpr string) *iSBN10Rule

ISBN10 is the validation function for validating if the field's value is a valid v10 ISBN.

func ISBN13

func ISBN13(fieldExpr string) *iSBN13Rule

ISBN13 is the validation function for validating if the field's value is a valid v13 ISBN.

func InFloat

func InFloat(filedExpr string, enum ...float64) *enumRuleFloat

InFloat checks if the filed is float and is in enum

func InInt

func InInt(filedExpr string, enum ...int) *enumRuleInt

InInt checks if the filed is int and is in enum

func InStr

func InStr(filedExpr string, enum ...string) *enumRuleString

InStr checks if the filed is string and is in enum

func InUint

func InUint(filedExpr string, enum ...uint) *enumRuleUint

InUint checks if the filed is uint and is in enum

func Ip

func Ip(fieldExpr string) *ipRule

Ip is the validation function for validating if the field's value is a valid v4 or v6 IP address.

func JSON

func JSON(fieldExpr string) *jsonRule

JSON is the validation function for validating if the current field's value is a valid json string.

func Length

func Length(fieldExpr string, ge int, le int) *lengthRule

Length checks if the filed is slice/array/string/map and its length is between [ge,le]

func Map

func Map(fieldExpr string, keyRule Rule, valueRule Rule) *mapRule

Map returns mapRule keyRule or valueRule can be nil if no need to check key/value

func NeComp

func NeComp(filedExpr string, inequivalent Comparable) *neRuleComp

NeComp checks if the field is Comparable and is not equal to given Comparable variable

func NeFloat

func NeFloat(filedExpr string, inequivalent float64) *neRuleFloat

NeFloat is the validation function for validating if the field's value is not equal to given float.

func NeInt

func NeInt(filedExpr string, inequivalent int) *neRuleInt

NeInt is the validation function for validating if the field's value is not equal to given int.

func NeStr

func NeStr(filedExpr string, inequivalent string) *neRuleString

NeStr is the validation function for validating if the field's value is not equal to given string.

func NeTime

func NeTime(filedExpr string, inequivalent time.Time) *neRuleTime

NeTime is the validation function for validating if the field's value is not equal to given timestamp.

func NeTimeStr

func NeTimeStr(filedExpr string, layout string, inequivalent time.Time) *neRuleTimeStr

NeTimeStr is the validation function for validating if the field's value string and is not equal to given timestamp.

func NeUint

func NeUint(filedExpr string, inequivalent uint) *neRuleUint

NeUint is the validation function for validating if the field's value is not equal to given uint.

func Nil

func Nil(fieldExpr string) *nilRule

Nil checks if the field is nil

func Not

func Not(innerRule Rule) *notRule

Not returns the opposite if innerRule

func Number

func Number(fieldExpr string) *regexRule

Number is the validation function for validating if the current field's value is a valid number.

func Numeric

func Numeric(fieldExpr string) *regexRule

Numeric is the validation function for validating if the current field's value is a valid numeric value.

func Or

func Or(rules ...Rule) *orRule

Or accepts slice of rules It failed when all rules failed

func RangeComp

func RangeComp(filedExpr string, ge Comparable, le Comparable) *rangeRuleComp

RangeComp checks if the value is between [ge,le]

func RangeFloat

func RangeFloat(filedExpr string, ge float64, le float64) *rangeRuleFloat

RangeFloat is the validation function for validating if the field's value is in given range.

func RangeInt

func RangeInt(filedExpr string, ge int, le int) *rangeRuleInt

RangeInt is the validation function for validating if the field's value is in given range.

func RangeTime

func RangeTime(filedExpr string, ge time.Time, le time.Time) *rangeRuleTime

RangeTime is the validation function for validating if the field's value is in given range.

func RangeTimeStr

func RangeTimeStr(filedExpr string, layout string, ge time.Time, le time.Time) *rangeRuleTimeStr

RangeTimeStr is the validation function for validating if the field's value is in given range.

func RangeUint

func RangeUint(filedExpr string, ge uint, le uint) *rangeRuleUint

RangeUint is the validation function for validating if the field's value is in given range.

func Regex

func Regex(fieldExpr string, regexExpr string) *regexRule

Regex is the validation function for validating if the current field's value satisfies regex pattern.

func StartsWith

func StartsWith(fieldExpr string, prefix string) *startsWithRule

StartsWith is the validation function for validating that the field's value starts with the text specified within the param.

func Time

func Time(fieldExpr string, layout string) *timeRule

Time is the validation function for validating if the current field's value is a valid datetime string.

func URI

func URI(fieldExpr string) *urlRule

URI is the validation function for validating if the current field's value is a valid URI.

func URL

func URL(fieldExpr string) *urlRule

URL is the validation function for validating if the current field's value is a valid URL.

func URLEncoded

func URLEncoded(fieldExpr string) *regexRule

URLEncoded is the validation function for validating if the current field's value is a valid encoded URL.

Types

type Checker

type Checker interface {
	Add(rule Rule, prompt string)
	Check(param interface{}) (bool, string, string)
}

Checker is the representation of validation object

func NewChecker

func NewChecker() Checker

NewChecker returns the Checker implementation

type Comparable

type Comparable interface {
	EqualTo(other interface{}) bool
	LessThan(other interface{}) bool
}

Comparable is the interface for sturcts to be compared in CrossComp

type Rule

type Rule interface {
	Check(param interface{}) (bool, string)

	Prompt(prompt string) Rule
	// contains filtered or unexported methods
}

Rule represents the restriction of param should satisfy

func HostNameRFC1123

func HostNameRFC1123(fieldExpr string) Rule

HostNameRFC1123 is the validation function for validating if the current field's value is a valid RFC1123 hostname.

Directories

Path Synopsis
_example

Jump to

Keyboard shortcuts

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