Golang parameter validation, which can replace go-playground/validator, includes ncluding Cross Field, Map, Slice and Array diving, provides readable,flexible, configurable validation.

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.

Owner
Similar Resources

A norms and conventions validator for Terraform

This tool will help you ensure that a terraform folder answer to your norms and conventions rules. This can be really useful in several cases : You're

Nov 29, 2022

:balloon: A lightweight struct validator for Go

gody Go versions supported Installation go get github.com/guiferpa/gody/v2 Usage package main import ( "encoding/json" "fmt" "net/http"

Nov 19, 2022

jio is a json schema validator similar to joi

jio is a json schema validator similar to joi

jio Make validation simple and efficient ! 中文文档 Why use jio? Parameter validation in Golang is really a cursing problem. Defining tags on structs is n

Dec 25, 2022

Checker/validator for Hong Kong IDs

hkidchecker Checker/validator for Hong Kong IDs Description This Go package validates Hong Kong ID card IDs. Useful for example for validating form in

Oct 13, 2021

OpenShift OLM Catalog Validator

OpenShift OLM Catalog Validator Overview It is an external validator which can be used with Operator-SDK to check the vendor-like criteria to publish

Nov 22, 2021

Vat ID Validator for Germany

German Vat Validator service This project has been developed using Hexagonal architecture and repository pattern. How to run? docker-compose up -d Cal

Nov 4, 2021

A demo project shows how to use validator to validate parameters

validator-demo This project is a demo project shows how to use validator to validate parameters use case install requirements go get github.com/favadi

Jan 10, 2022

A lightweight model validator written in Go.

validator A lightweight model validator written in Go. quickstart package main import ( "fmt" v "github.com/go-the-way/validator" ) func main() {

Sep 27, 2022

Library providing opanapi3 and Go types for store/validation and transfer of ISO-4217, ISO-3166, and other types.

go-types This library has been created with the purpose to facilitate the store, validation, and transfer of Go ISO-3166/ISO-4217/timezones/emails/URL

Nov 9, 2022
Gin Middleware to extract json tag value from playground validator's errors validation

Json Tag Extractor for Go-Playground Validator This is Gin Middleware that aim to extract json tag and than store it to FieldError.Field() object. Ins

Jan 14, 2022
Validator - Replace the validation framework used by gin

validator Replace the validation framework used by gin replace mod:replace githu

Jan 18, 2022
An idiomatic Go (golang) validation package. Supports configurable and extensible validation rules (validators) using normal language constructs instead of error-prone struct tags.

ozzo-validation Description ozzo-validation is a Go package that provides configurable and extensible data validation capabilities. It has the followi

Jan 7, 2023
Snake-validator - Snake validator with golang

snake-validator Overview The concept of Snake (the video game) has been around s

Jan 22, 2022
The Hyperscale InputFilter library provides a simple inputfilter chaining mechanism by which multiple filters and validator may be applied to a single datum in a user-defined order.

Hyperscale InputFilter Branch Status Coverage master The Hyperscale InputFilter library provides a simple inputfilter chaining mechanism by which mult

Oct 20, 2021
An interesting go struct tag expression syntax for field validation, etc.

go-tagexpr An interesting go struct tag expression syntax for field validation, etc. Usage Validator: A powerful validator that supports struct tag ex

Jan 9, 2023
Dec 28, 2022
golang request validator

validator Golang 参数验证器,目前只支持POST请求,JSON格式参数验证 亮点 1、验证时只要有一个错误,错误信息立即返回 2、可自定义参数别名显示错误信息;详情见_example文件 使用 go mod -u github.com/one-gold-coin/validator

Sep 30, 2021
golang rule-based string validator

gosv golang rule-based string validator usage import "github.com/s0rg/gosv" var MyRules = []gosv.Rule{ gosv.MinLen(8), gosv.MaxLen(64), gosv.MinLo

Nov 20, 2021
Iran National Id, Bank Card Number, Mobile Number Validator for golang

Iran IDValidator Iran National Id, Bank Card Number, Mobile Number Validator for golang Installation go get -u github.com/mohammadv184/idvalidator Us

Dec 20, 2021