All Projects → liangyaopei → checker

liangyaopei / checker

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

Programming Languages

go
31211 projects - #10 most used programming language

Projects that are alternatives of or similar to checker

Validate
⚔ Go package for data validation and filtering. support Map, Struct, Form data. Go通用的数据验证与过滤库,使用简单,内置大部分常用验证、过滤器,支持自定义验证器、自定义消息、字段翻译。
Stars: ✭ 378 (+509.68%)
Mutual labels:  validation, validator, verification, validate
Validator.js
String validation
Stars: ✭ 18,842 (+30290.32%)
Mutual labels:  validation, validator, validate
Validate
A simple jQuery plugin to validate forms.
Stars: ✭ 298 (+380.65%)
Mutual labels:  validation, validator, validate
python-valid8
Yet another validation lib ;). Provides tools for general-purpose variable validation, function inputs/outputs validation as well as class fields validation. All entry points raise consistent ValidationError including all contextual details, with dynamic inheritance of ValueError/TypeError as appropriate.
Stars: ✭ 24 (-61.29%)
Mutual labels:  validation, validator, validate
Validator.js
⁉️轻量级的 JavaScript 表单验证,字符串验证。没有依赖,支持 UMD ,~3kb。
Stars: ✭ 486 (+683.87%)
Mutual labels:  validation, validator, validate
Nice Validator
Simple, smart and pleasant validation solution.
Stars: ✭ 587 (+846.77%)
Mutual labels:  validation, validator, validate
Vee Validate
✅ Form Validation for Vue.js
Stars: ✭ 8,820 (+14125.81%)
Mutual labels:  validation, validator, validate
validate-framework
validate-framework:一款轻量、无依赖的 JavaScript 验证组件
Stars: ✭ 55 (-11.29%)
Mutual labels:  validator, validate
govalidators
struct 验证器,内置大部分常用验证,可自定义
Stars: ✭ 56 (-9.68%)
Mutual labels:  validator, govalidator
node-input-validator
Validation library for node.js
Stars: ✭ 74 (+19.35%)
Mutual labels:  validation, validator
pyvaru
Rule based data validation library for python 3.
Stars: ✭ 17 (-72.58%)
Mutual labels:  validation, validator
vayder
Easy and concise validations for Express routes
Stars: ✭ 26 (-58.06%)
Mutual labels:  validator, validate
valite
🔥 Concurrently execute your validators in a simple, practical and light validator engine.
Stars: ✭ 20 (-67.74%)
Mutual labels:  validator, validate
validation
Aplus Framework Validation Library
Stars: ✭ 99 (+59.68%)
Mutual labels:  validation, validator
FilterInputJs
Tiny and Powerful Library for limit an entry (text box,input) as number,string or more...
Stars: ✭ 37 (-40.32%)
Mutual labels:  validator, validate
Maat
Validation and transformation library powered by deductive ascending parser. Made to be extended for any kind of project.
Stars: ✭ 27 (-56.45%)
Mutual labels:  validation, validator
Password Validator
Validates password according to flexible and intuitive specification
Stars: ✭ 224 (+261.29%)
Mutual labels:  validation, validate
openui5-validator
A library to validate OpenUI5 fields
Stars: ✭ 17 (-72.58%)
Mutual labels:  validation, validator
filter
Go语言的数据过滤包,由 数据输入、格式化、校验、输出 几个部份组成。
Stars: ✭ 22 (-64.52%)
Mutual labels:  validation, validator
dockerfile-utils
A library and command line interface for formatting and linting Dockerfiles.
Stars: ✭ 17 (-72.58%)
Mutual labels:  validation, validator

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.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].