validate

package module
v1.5.1 Latest Latest
Warning

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

Go to latest
Published: Jan 12, 2024 License: MIT Imports: 26 Imported by: 0

README

Validate

GitHub tag (latest SemVer) GoDoc GitHub go.mod Go version Coverage Status Go Report Card Actions Status

validate is a generic Go data validate and filter tool library.

  • Support quick validate Map, Struct, Request(Form, JSON, url.Values, UploadedFile) data
    • Validating http.Request automatically collects data based on the request Content-Type value
    • Supports checking each child value in a slice. eg: v.StringRule("tags.*", "required|string")
  • Support filter/sanitize/convert data before validate
  • Support add custom filter/validator func
  • Support scene settings, verify different fields in different scenes
  • Support custom error messages, field translates.
    • Can use message, label tags in struct
  • Customizable i18n aware error messages, built in en, zh-CN, zh-TW
  • Built-in common data type filter/converter. see Built In Filters
  • Many commonly used validators have been built in(> 70), see Built In Validators
  • Can use validate in any frameworks, such as Gin, Echo, Chi and more
  • Supports direct use of rules to validate value. eg: validate.Val("xyz@mail.com", "required|email")

中文说明

中文说明请查看 README.zh-CN

Go Doc

Validate Struct

Use the validate tag of the structure, you can quickly config a structure.

Config the struct use tags

Field translations and error messages for structs can be quickly configured using the message and label tags.

  • Support configuration field mapping through structure tag, read the value of json tag by default
  • Support configuration error message via structure's message tag
  • Support configuration field translation via structure's label tag
package main

import (
	"fmt"
	"time"

	"github.com/gookit/validate"
)

// UserForm struct
type UserForm struct {
	Name     string    `validate:"required|min_len:7" message:"required:{field} is required" label:"User Name"`
	Email    string    `validate:"email" message:"email is invalid" label:"User Email"`
	Age      int       `validate:"required|int|min:1|max:99" message:"int:age must int|min:age min value is 1"`
	CreateAt int       `validate:"min:1"`
	Safe     int       `validate:"-"`
	UpdateAt time.Time `validate:"required" message:"update time is required"`
	Code     string    `validate:"customValidator"`
	// ExtInfo nested struct
	ExtInfo struct{
		Homepage string `validate:"required" label:"Home Page"`
		CityName string
	} `validate:"required" label:"Home Page"`
}

// CustomValidator custom validator in the source struct.
func (f UserForm) CustomValidator(val string) bool {
	return len(val) == 4
}
Config validate use struct methods

validate provides extended functionality:

The struct can implement three interfaces methods, which is convenient to do some customization:

  • ConfigValidation(v *Validation) will be called after the validator instance is created
  • Messages() map[string]string can customize the validator error message
  • Translates() map[string]string can customize field translation
package main

import (
	"fmt"
	"time"

	"github.com/gookit/validate"
)

// UserForm struct
type UserForm struct {
	Name     string    `validate:"required|min_len:7"`
	Email    string    `validate:"email"`
	Age      int       `validate:"required|int|min:1|max:99"`
	CreateAt int       `validate:"min:1"`
	Safe     int       `validate:"-"`
	UpdateAt time.Time `validate:"required"`
	Code     string    `validate:"customValidator"`
	// ExtInfo nested struct
	ExtInfo struct{
		Homepage string `validate:"required"`
		CityName string
	} `validate:"required"`
}

// CustomValidator custom validator in the source struct.
func (f UserForm) CustomValidator(val string) bool {
	return len(val) == 4
}

// ConfigValidation config the Validation
// eg:
// - define validate scenes
func (f UserForm) ConfigValidation(v *validate.Validation) {
	v.WithScenes(validate.SValues{
		"add":    []string{"ExtInfo.Homepage", "Name", "Code"},
		"update": []string{"ExtInfo.CityName", "Name"},
	})
}

// Messages you can custom validator error messages. 
func (f UserForm) Messages() map[string]string {
	return validate.MS{
		"required": "oh! the {field} is required",
		"email": "email is invalid",
		"Name.required": "message for special field",
		"Age.int": "age must int",
		"Age.min": "age min value is 1",
	}
}

// Translates you can custom field translates. 
func (f UserForm) Translates() map[string]string {
	return validate.MS{
		"Name": "User Name",
		"Email": "User Email",
		"ExtInfo.Homepage": "Home Page",
	}
}
Create and validating

Can use validate.Struct(ptr) quick create a validation instance. then call v.Validate() for validating.

package main

import (
  "fmt"

  "github.com/gookit/validate"
)

func main() {
	u := &UserForm{
		Name: "inhere",
	}
	
	v := validate.Struct(u)
	// v := validate.New(u)

	if v.Validate() { // validate ok
		// do something ...
	} else {
		fmt.Println(v.Errors) // all error messages
		fmt.Println(v.Errors.One()) // returns a random error message text
		fmt.Println(v.Errors.OneError()) // returns a random error
		fmt.Println(v.Errors.Field("Name")) // returns error messages of the field 
	}
}

Validate Map

You can also validate a MAP data directly.

package main

import (
"fmt"

"github.com/gookit/validate"
)

func main()  {
	m := map[string]any{
		"name":  "inhere",
		"age":   100,
		"oldSt": 1,
		"newSt": 2,
		"email": "some@email.com",
		"tags": []string{"go", "php", "java"},
	}

	v := validate.Map(m)
	// v := validate.New(m)
	v.AddRule("name", "required")
	v.AddRule("name", "minLen", 7)
	v.AddRule("age", "max", 99)
	v.AddRule("age", "min", 1)
	v.AddRule("email", "email")
	
	// can also
	v.StringRule("age", "required|int|min:1|max:99")
	v.StringRule("name", "required|minLen:7")
	v.StringRule("tags", "required|slice|minlen:1")
	// feat: support check sub-item in slice
	v.StringRule("tags.*", "required|string|min_len:7")

	// v.WithScenes(map[string]string{
	//	 "create": []string{"name", "email"},
	//	 "update": []string{"name"},
	// })
	
	if v.Validate() { // validate ok
		safeData := v.SafeData()
		// do something ...
	} else {
		fmt.Println(v.Errors) // all error messages
		fmt.Println(v.Errors.One()) // returns a random error message text
	}
}

Validate Request

If it is an HTTP request, you can quickly validate the data and pass the verification. Then bind the secure data to the structure.

package main

import (
	"fmt"
	"net/http"
	"time"

	"github.com/gookit/validate"
)

// UserForm struct
type UserForm struct {
	Name     string
	Email    string
	Age      int
	CreateAt int
	Safe     int
	UpdateAt time.Time
	Code     string
}

func main()  {
	handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		data, err := validate.FromRequest(r)
		if err != nil {
			panic(err)
		}

		v := data.Create()
		// setting rules
		v.FilterRule("age", "int") // convert value to int
		
		v.AddRule("name", "required")
		v.AddRule("name", "minLen", 7)
		v.AddRule("age", "max", 99)
		v.StringRule("code", `required|regex:\d{4,6}`)

		if v.Validate() { // validate ok
			// safeData := v.SafeData()
			userForm := &UserForm{}
			v.BindSafeData(userForm)

			// do something ...
			fmt.Println(userForm.Name)
		} else {
			fmt.Println(v.Errors) // all error messages
			fmt.Println(v.Errors.One()) // returns a random error message text
		}
	})

	http.ListenAndServe(":8090", handler)
}

Quick Method

Quick create Validation instance.

  • New(data any, scene ...string) *Validation
  • Request(r *http.Request) *Validation
  • JSON(s string, scene ...string) *Validation
  • Struct(s any, scene ...string) *Validation
  • Map(m map[string]any, scene ...string) *Validation

Quick create DataFace instance.

  • FromMap(m map[string]any) *MapData
  • FromStruct(s any) (*StructData, error)
  • FromJSON(s string) (*MapData, error)
  • FromJSONBytes(bs []byte) (*MapData, error)
  • FromURLValues(values url.Values) *FormData
  • FromRequest(r *http.Request, maxMemoryLimit ...int64) (DataFace, error)

Create Validation from DataFace

d := FromMap(map[string]any{"key": "val"})
v := d.Validation()
Methods In Validation
  • func (v *Validation) Validate(scene ...string) bool Do validating and return is success.
  • func (v *Validation) ValidateE(scene ...string) Errors Do validating and return error.

More Usage

Validate Error

v.Errors is map data, top key is field name, value is map[string]string.

// do validating
if v.Validate() {
	return nil
}

// get errors
es := v.Errors

// check
es.Empty() // bool

// returns an random error, if no error returns nil
fmt.Println(v.Errors.OneError())
fmt.Println(v.Errors.ErrOrNil())

fmt.Println(v.Errors) // all error messages
fmt.Println(v.Errors.One()) // returns a random error message text
fmt.Println(v.Errors.Field("Name")) // returns error messages of the field 

Encode to JSON:

  • StopOnError=true(default), will only one error
{
    "field1": {
        "required": "error msg0"
    }
}
  • if StopOnError=false, will get multi error
{
    "field1": {
        "minLen": "error msg1",
        "required": "error msg0"
    },
    "field2": {
        "min": "error msg2"
    }
}
Global Option

You can adjust some processing logic of the validator by changing the global option settings.

// GlobalOption settings for validate
type GlobalOption struct {
	// FilterTag name in the struct tags.
	//
	// default: filter
	FilterTag string
	// ValidateTag in the struct tags.
	//
	// default: validate
	ValidateTag string
	// FieldTag the output field name in the struct tags.
	// it as placeholder on error message.
	//
	// default: json
	FieldTag string
	// LabelTag the display name in the struct tags.
	// use for define field translate name on error.
	//
	// default: label
	LabelTag string
	// MessageTag define error message for the field.
	//
	// default: message
	MessageTag string
	// StopOnError If true: An error occurs, it will cease to continue to verify
	StopOnError bool
	// SkipOnEmpty Skip check on field not exist or value is empty
	SkipOnEmpty bool
	// UpdateSource Whether to update source field value, useful for struct validate
	UpdateSource bool
	// CheckDefault Whether to validate the default value set by the user
	CheckDefault bool
	// CheckZero Whether validate the default zero value. (intX,uintX: 0, string: "")
	CheckZero bool
	// CheckSubOnParentMarked True: only collect sub-struct rule on current field has rule.
	CheckSubOnParentMarked bool
	// ValidatePrivateFields Whether to validate private fields or not, especially when inheriting other other structs.
	//
	//  type foo struct {
	//	  Field int `json:"field" validate:"required"`
	//  }
	//  type bar struct {
	//    foo // <-- validate this field
	//    Field2 int `json:"field2" validate:"required"`
	//  }
	//
	// default: false
	ValidatePrivateFields bool
}

Usage:

// change global opts
validate.Config(func(opt *validate.GlobalOption) {
	opt.StopOnError = false
	opt.SkipOnEmpty = false
})
Validating Private (Unexported fields)

By default, private fields are skipped. It is not uncommon to find code such as the following

type foo struct {
	somefield int
}

type Bar struct {
	foo
	SomeOtherField string
}

In order to have foo.somefield validated, enable the behavior by setting GlobalOption.ValidatePrivateFields to true.

validate.Config(func(opt *validate.GlobalOption) {
	opt.ValidatePrivateFields = true
})

Custom Error Messages
  • Register language messages
import "github.com/gookit/validate/locales/zhcn"

// for all Validation.
// NOTICE: must be registered before on validate.New(), it only need call at once.
zhcn.RegisterGlobal()

// ... ...

v := validate.New()

// only for current Validation
zhcn.Register(v)
  • Manual add global messages
validate.AddGlobalMessages(map[string]string{
    "minLength": "OO! {field} min length is %d",
})
  • Add messages for current validation
v := validate.New(map[string]any{
    "name": "inhere",
})
v.StringRule("name", "required|string|minLen:7|maxLen:15")

v.AddMessages(map[string]string{
    "minLength": "OO! {field} min length is %d",
    "name.minLen": "OO! username min length is %d",
})
  • Use struct tags: message, label
type UserForm struct {
    Name  string `validate:"required|minLen:7" label:"User Name"`
    Email string `validate:"email" message:"email is invalid" label:"User Email"`
}
  • Use struct method Messages()
// Messages you can custom validator error messages. 
func (f UserForm) Messages() map[string]string {
	return validate.MS{
		"required": "oh! the {field} is required",
		"Name.required": "message for special field",
	}
}
Add Custom Validator

validate supports adding custom validators, and supports adding global validator and temporary validator.

  • Global Validator is globally valid and can be used everywhere
  • Temporary Validator added to the current validation instance, only the current validation is available
  • Add verification method to the structure. How to use please see the structure verification example above

Note: The validator method must return a bool to indicate whether the validation was successful. The first parameter is the corresponding field value. If there are additional parameters, they will be appended automatically.

Add Global Validator

You can add one or more custom validators at once.

validate.AddValidator("myCheck0", func(val any) bool {
	// do validate val ...
	return true
})
validate.AddValidators(validate.M{
	"myCheck1": func(val any) bool {
		// do validate val ...
		return true
	},
})
Add Temporary Validator

Again, you can add one or more custom validators at once.

v := validate.Struct(u)
v.AddValidator("myFunc3", func(val any) bool {
	// do validate val ...
	return true
})
v.AddValidators(validate.M{
	"myFunc4": func(val any) bool {
		// do validate val ...
		return true
	},
})
Add Custom Filter

validate can also support adding custom filters, and supports adding global filter and temporary filter.

  • Global Filter is globally valid and can be used everywhere
  • Temporary Filter added to the current validation instance, only the current validation is available

TIP: for filter func, we allow functions with 1 result or 2 results where the second is an error.

Add Global Filter

You can add one or more custom validators at once.

package main

import "github.com/gookit/validate"

func init() {
	validate.AddFilter("myToIntFilter0", func(val any) int {
		// do filtering val ...
		return 1
	})
	validate.AddFilters(validate.M{
		"myToIntFilter1": func(val any) (int, error) {
			// do filtering val ...
			return 1, nil
		},
	})
}
Add Temporary Filter

Again, you can add one or more custom filters at once.

package main

import "github.com/gookit/validate"

func main() {
	v := validate.New(&someStrcut{})

	v.AddFilter("myToIntFilter0", func(val any) int {
		// do filtering val ...
		return 1
	})
	v.AddFilters(validate.M{
		"myToIntFilter1": func(val any) (int, error) {
			// do filtering val ...
			return 1, nil
		},
	})
}
Custom required validation

Allows a custom required validator to customize whether the validation is empty. However, note that the validator name must start with required, e.g. required_custom.

	type Data struct {
		Age  int    `validate:"required_custom" message:"age is required"`
		Name string `validate:"required"`
	}

	v := validate.New(&Data{
		Name: "tom",
		Age:  0,
	})

	v.AddValidator("required_custom", func(val any) bool {
		// do check value
		return false
	})

	ok := v.Validate()
	assert.False(t, ok)

Use on gin framework

Can use validate in any frameworks, such as Gin, Echo, Chi and more.

Examples on gin:

package main
import (
    "github.com/gin-gonic/gin/binding"
    "github.com/gookit/validate"
)

// implements the binding.StructValidator
type customValidator struct {}

func (c *customValidator) ValidateStruct(ptr any) error {
    v := validate.Struct(ptr)
    v.Validate() // do validating
    
    if v.Errors.Empty() {
	return nil
    }

    return v.Errors
}

func (c *customValidator) Engine() any {
    return nil
}

func main()  {
	// ...

    // after init gin, set custom validator
    binding.Validator = &customValidator{}
}

Built In Validators

Camel-style validator names now have underlined aliases. endsWith can also be written as ends_with

validator/aliases description
required Check value is required and cannot be empty.
required_if/requiredIf required_if:anotherfield,value,... The field under validation must be present and not empty if the anotherField field is equal to any value.
requiredUnless required_unless:anotherfield,value,... The field under validation must be present and not empty unless the anotherField field is equal to any value.
requiredWith required_with:foo,bar,... The field under validation must be present and not empty only if any of the other specified fields are present.
requiredWithAll required_with_all:foo,bar,... The field under validation must be present and not empty only if all of the other specified fields are present.
requiredWithout required_without:foo,bar,... The field under validation must be present and not empty only when any of the other specified fields are not present.
requiredWithoutAll required_without_all:foo,bar,... The field under validation must be present and not empty only when all of the other specified fields are not present.
-/safe The field values are safe and do not require validation
int/integer/isInt Check value is intX uintX type, And support size checking. eg: "int" "int:2" "int:2,12"
uint/isUint Check value is uint(uintX) type, value >= 0
bool/isBool Check value is bool string(true: "1", "on", "yes", "true", false: "0", "off", "no", "false").
string/isString Check value is string type.
float/isFloat Check value is float(floatX) type
slice/isSlice Check value is slice type([]intX []uintX []byte []string ...).
in/enum Check if the value is in the given enumeration "in:a,b"
not_in/notIn Check if the value is not in the given enumeration "contains:b"
contains Check if the input value contains the given value
not_contains/notContains Check if the input value not contains the given value
string_contains/stringContains Check if the input string value is contains the given sub-string
starts_with/startsWith Check if the input string value is starts with the given sub-string
ends_with/endsWith Check if the input string value is ends with the given sub-string
range/between Check that the value is a number and is within the given range
max/lte Check value is less than or equal to the given value
min/gte Check value is greater than or equal to the given value(for intX uintX floatX)
eq/equal/isEqual Check that the input value is equal to the given value
ne/notEq/notEqual Check that the input value is not equal to the given value
lt/lessThan Check value is less than the given value(use for intX uintX floatX)
gt/greaterThan Check value is greater than the given value(use for intX uintX floatX)
email/isEmail Check value is email address string.
intEq/intEqual Check value is int and equals to the given value.
len/length Check value length is equals to the given size(use for string array slice map).
regex/regexp Check if the value can pass the regular verification
arr/list/array/isArray Check value is array, slice type
map/isMap Check value is a MAP type
strings/isStrings Check value is string slice type(only allow []string).
ints/isInts Check value is int slice type(only allow []int).
min_len/minLen/minLength Check the minimum length of the value is the given size
max_len/maxLen/maxLength Check the maximum length of the value is the given size
eq_field/eqField Check that the field value is equals to the value of another field
ne_field/neField Check that the field value is not equals to the value of another field
gte_field/gteField Check that the field value is greater than or equal to the value of another field
gt_field/gtField Check that the field value is greater than the value of another field
lte_field/lteField Check if the field value is less than or equal to the value of another field
lt_field/ltField Check that the field value is less than the value of another field
file/isFile Verify if it is an uploaded file
image/isImage Check if it is an uploaded image file and support suffix check
mime/mimeType/inMimeTypes Check that it is an uploaded file and is in the specified MIME type
date/isDate Check the field value is date string. eg 2018-10-25
gt_date/gtDate/afterDate Check that the input value is greater than the given date string.
lt_date/ltDate/beforeDate Check that the input value is less than the given date string
gte_date/gteDate/afterOrEqualDate Check that the input value is greater than or equal to the given date string.
lte_date/lteDate/beforeOrEqualDate Check that the input value is less than or equal to the given date string.
has_whitespace/hasWhitespace Check value string has Whitespace.
ascii/ASCII/isASCII Check value is ASCII string.
alpha/isAlpha Verify that the value contains only alphabetic characters
alphaNum/isAlphaNum Check that only letters, numbers are included
alphaDash/isAlphaDash Check to include only letters, numbers, dashes ( - ), and underscores ( _ )
multiByte/isMultiByte Check value is MultiByte string.
base64/isBase64 Check value is Base64 string.
dns_name/dnsName/DNSName/isDNSName Check value is DNSName string.
data_uri/dataURI/isDataURI Check value is DataURI string.
empty/isEmpty Check value is Empty string.
hex_color/hexColor/isHexColor Check value is Hex color string.
hexadecimal/isHexadecimal Check value is Hexadecimal string.
json/JSON/isJSON Check value is JSON string.
lat/latitude/isLatitude Check value is Latitude string.
lon/longitude/isLongitude Check value is Longitude string.
mac/isMAC Check value is MAC string.
num/number/isNumber Check value is number string. >= 0
cn_mobile/cnMobile/isCnMobile Check value is china mobile number string.
printableASCII/isPrintableASCII Check value is PrintableASCII string.
rgb_color/rgbColor/RGBColor/isRGBColor Check value is RGB color string.
url/isURL Check value is URL string.
fullUrl/isFullURL Check value is full URL string(must start with http,https).
ip/isIP Check value is IP(v4 or v6) string.
ipv4/isIPv4 Check value is IPv4 string.
ipv6/isIPv6 Check value is IPv6 string.
CIDR/isCIDR Check value is CIDR string.
CIDRv4/isCIDRv4 Check value is CIDRv4 string.
CIDRv6/isCIDRv6 Check value is CIDRv6 string.
uuid/isUUID Check value is UUID string.
uuid3/isUUID3 Check value is UUID3 string.
uuid4/isUUID4 Check value is UUID4 string.
uuid5/isUUID5 Check value is UUID5 string.
filePath/isFilePath Check value is an existing file path
unixPath/isUnixPath Check value is Unix Path string.
winPath/isWinPath Check value is Windows Path string.
isbn10/ISBN10/isISBN10 Check value is ISBN10 string.
isbn13/ISBN13/isISBN13 Check value is ISBN13 string.

Notice:

  • intX is contains: int, int8, int16, int32, int64
  • uintX is contains: uint, uint8, uint16, uint32, uint64
  • floatX is contains: float32, float64

Built In Filters

Filters powered by: gookit/filter

filter/aliases description
int/toInt Convert value(string/intX/floatX) to int type v.FilterRule("id", "int")
uint/toUint Convert value(string/intX/floatX) to uint type v.FilterRule("id", "uint")
int64/toInt64 Convert value(string/intX/floatX) to int64 type v.FilterRule("id", "int64")
float/toFloat Convert value(string/intX/floatX) to float type
bool/toBool Convert string value to bool. (true: "1", "on", "yes", "true", false: "0", "off", "no", "false")
trim/trimSpace Clean up whitespace characters on both sides of the string
ltrim/trimLeft Clean up whitespace characters on left sides of the string
rtrim/trimRight Clean up whitespace characters on right sides of the string
int/integer Convert value(string/intX/floatX) to int type v.FilterRule("id", "int")
lower/lowercase Convert string to lowercase
upper/uppercase Convert string to uppercase
lcFirst/lowerFirst Convert the first character of a string to lowercase
ucFirst/upperFirst Convert the first character of a string to uppercase
ucWord/upperWord Convert the first character of each word to uppercase
camel/camelCase Convert string to camel naming style
snake/snakeCase Convert string to snake naming style
escapeJs/escapeJS Escape JS string.
escapeHtml/escapeHTML Escape HTML string.
str2ints/strToInts Convert string to int slice []int
str2time/strToTime Convert date string to time.Time.
str2arr/str2array/strToArray Convert string to string slice []string

Gookit packages

  • gookit/ini Go config management, use INI files
  • gookit/rux Simple and fast request router for golang HTTP
  • gookit/gcli build CLI application, tool library, running CLI commands
  • gookit/event Lightweight event manager and dispatcher implements by Go
  • gookit/cache Generic cache use and cache manager for golang. support File, Memory, Redis, Memcached.
  • gookit/config Go config management. support JSON, YAML, TOML, INI, HCL, ENV and Flags
  • gookit/color A command-line color library with true color support, universal API methods and Windows support
  • gookit/filter Provide filtering, sanitizing, and conversion of golang data
  • gookit/validate Use for data validation and filtering. support Map, Struct, Form data
  • gookit/goutil Some utils for the Go: string, array/slice, map, format, cli, env, filesystem, test and more
  • More please see https://github.com/gookit

See also

License

MIT

Documentation

Overview

Package validate is a generic go data validate, filtering library.

Source code and other details for the project are available at GitHub:

https://github.com/gookit/validate

Index

Constants

View Source
const (
	RuleRequired = "required"
	RuleRegexp   = "regexp"
)

some commonly validation rule names.

View Source
const (
	Email        = `` /* 150-byte string literal not displayed */
	UUID3        = "^[0-9a-f]{8}-[0-9a-f]{4}-3[0-9a-f]{3}-[0-9a-f]{4}-[0-9a-f]{12}$"
	UUID4        = "^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"
	UUID5        = "^[0-9a-f]{8}-[0-9a-f]{4}-5[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"
	UUID         = "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$"
	Int          = "^(?:[-+]?(?:0|[1-9][0-9]*))$"
	Float        = "^(?:[-+]?(?:[0-9]+))?(?:\\.[0-9]*)?(?:[eE][\\+\\-]?(?:[0-9]+))?$"
	RGBColor     = "" /* 157-byte string literal not displayed */
	FullWidth    = "[^\u0020-\u007E\uFF61-\uFF9F\uFFA0-\uFFDC\uFFE8-\uFFEE0-9a-zA-Z]"
	HalfWidth    = "[\u0020-\u007E\uFF61-\uFF9F\uFFA0-\uFFDC\uFFE8-\uFFEE0-9a-zA-Z]"
	Base64       = "^(?:[A-Za-z0-9+\\/]{4})*(?:[A-Za-z0-9+\\/]{2}==|[A-Za-z0-9+\\/]{3}=|[A-Za-z0-9+\\/]{4})$"
	Latitude     = "^[-+]?([1-8]?\\d(\\.\\d+)?|90(\\.0+)?)$"
	Longitude    = "^[-+]?(180(\\.0+)?|((1[0-7]\\d)|([1-9]?\\d))(\\.\\d+)?)$"
	DNSName      = `^([a-zA-Z0-9_]{1}[a-zA-Z0-9_-]{0,62}){1}(\.[a-zA-Z0-9_]{1}[a-zA-Z0-9_-]{0,62})*[\._]?$`
	FullURL      = `^(?:ftp|tcp|udp|wss?|https?):\/\/[\w\.\/#=?&-_%]+$`
	URLSchema    = `((ftp|tcp|udp|wss?|https?):\/\/)`
	URLUsername  = `(\S+(:\S*)?@)`
	URLPath      = `((\/|\?|#)[^\s]*)`
	URLPort      = `(:(\d{1,5}))`
	URLIP        = `([1-9]\d?|1\d\d|2[01]\d|22[0-3])(\.(1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.([0-9]\d?|1\d\d|2[0-4]\d|25[0-4]))`
	URLSubdomain = `((www\.)|([a-zA-Z0-9]+([-_\.]?[a-zA-Z0-9])*[a-zA-Z0-9]\.[a-zA-Z0-9]+))`
	WinPath      = `^[a-zA-Z]:\\(?:[^\\/:*?"<>|\r\n]+\\)*[^\\/:*?"<>|\r\n]*$`
	UnixPath     = `^(/[^/\x00]*)+/?$`
)

Basic regular expressions for validating strings. (there are from package "asaskevich/govalidator")

Variables

View Source
var (
	Marshal MarshalFunc = json.Marshal
	//original
	// Unmarshal UnmarshalFunc = json.Unmarshal
	// Modified
	// Customization: use custom JSON Unmarshal to handle all unmarshalling errors.
	Unmarshal UnmarshalFunc = jsonutil.Unmarshal
)

data (Un)marshal func

View Source
var (
	ErrUnaddressableField = errors.New("cannot set value as it was not passed-by-reference")
	ErrNoField            = errors.New("field not exist in the source data")

	ErrEmptyData   = errors.New("please input data use for validate")
	ErrInvalidData = errors.New("invalid input data")
)

some internal error definition

View Source
var (
	// DefaultFieldName for value validate.
	DefaultFieldName = "input"
)
View Source
var ErrConvertFail = errors.New("convert value is failure")

ErrConvertFail error

View Source
var NilValue = reflect.Zero(reflect.TypeOf((*any)(nil)).Elem())

NilValue TODO a reflect nil value, use for instead of nilRVal

Functions

func AddBuiltinMessages

func AddBuiltinMessages(mp map[string]string)

AddBuiltinMessages alias of the AddGlobalMessages()

func AddFilter

func AddFilter(name string, filterFunc any)

AddFilter add global filter to the pkg.

func AddFilters

func AddFilters(m map[string]any)

AddFilters add global filters

func AddGlobalMessages

func AddGlobalMessages(mp map[string]string)

AddGlobalMessages add global builtin messages

func AddValidator

func AddValidator(name string, checkFunc any)

AddValidator to the pkg. checkFunc must return a bool

Usage:

v.AddValidator("myFunc", func(val any) bool {
	// do validate val ...
	return true
})

func AddValidators

func AddValidators(m map[string]any)

AddValidators to the global validators map

func AfterDate

func AfterDate(srcDate, dstDate string) bool

AfterDate check

func AfterOrEqualDate

func AfterOrEqualDate(srcDate, dstDate string) bool

AfterOrEqualDate check

func BeforeDate

func BeforeDate(srcDate, dstDate string) bool

BeforeDate check

func BeforeOrEqualDate

func BeforeOrEqualDate(srcDate, dstDate string) bool

BeforeOrEqualDate check

func Between

func Between(val any, min, max int64) bool

Between int value in the given range. only check for: int(X), uint(X).

func BuiltinMessages

func BuiltinMessages() map[string]string

BuiltinMessages get builtin messages

func ByteLength

func ByteLength(str string, minLen int, maxLen ...int) bool

ByteLength check string's length

func CalcLength

func CalcLength(val any) int

CalcLength for input value

func CallByValue

func CallByValue(fv reflect.Value, args ...any) []reflect.Value

CallByValue call func by reflect.Value

func Config

func Config(fn func(opt *GlobalOption))

Config global options

func Contains

func Contains(s, sub any) bool

Contains check that the specified string, list(array, slice) or map contains the specified substring or element.

Notice: list check value exist. map check key exist.

func CopyGlobalMessages

func CopyGlobalMessages() map[string]string

CopyGlobalMessages copy get builtin messages

func DateFormat

func DateFormat(s string, layout string) bool

DateFormat check

func EndsWith

func EndsWith(s, sub string) bool

EndsWith check string is ends with sub-string

func Enum

func Enum(val, enum any) bool

Enum value(int(X),string) should be in the given enum(strings, ints, uints).

func Gt

func Gt(val, min any) bool

Gt check value greater dst value.

only check for: int(X), uint(X), float(X), string.

func Gte

func Gte(val, min any) bool

Gte check value greater or equal dst value only check for: int(X), uint(X), float(X), string.

func HasLowerCase

func HasLowerCase(s string) bool

HasLowerCase check string has lower case

func HasURLSchema

func HasURLSchema(s string) bool

HasURLSchema string.

func HasUpperCase

func HasUpperCase(s string) bool

HasUpperCase check string has upper case

func HasWhitespace

func HasWhitespace(s string) bool

HasWhitespace check. eg "10"

func IntEqual

func IntEqual(val any, wantVal int64) bool

IntEqual check

func IsASCII

func IsASCII(s string) bool

IsASCII string.

func IsAlpha

func IsAlpha(s string) bool

IsAlpha string.

func IsAlphaDash

func IsAlphaDash(s string) bool

IsAlphaDash string.

func IsAlphaNum

func IsAlphaNum(s string) bool

IsAlphaNum string.

func IsArray

func IsArray(val any, strict ...bool) (ok bool)

IsArray check value is array or slice.

func IsBase64

func IsBase64(s string) bool

IsBase64 string.

func IsBool

func IsBool(val any) bool

IsBool check. allow: bool, string.

func IsCIDR

func IsCIDR(s string) bool

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

func IsCIDRv4

func IsCIDRv4(s string) bool

IsCIDRv4 is the validation function for validating if the field's value is a valid v4 CIDR address.

func IsCIDRv6

func IsCIDRv6(s string) bool

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

func IsCnMobile

func IsCnMobile(s string) bool

IsCnMobile string.

func IsDNSName

func IsDNSName(s string) bool

IsDNSName string.

func IsDataURI

func IsDataURI(s string) bool

IsDataURI string.

data:[<mime type>] ( [;charset=<charset>] ) [;base64],码内容 eg. "data:image/gif;base64,R0lGODlhA..."

func IsDate

func IsDate(srcDate string) bool

IsDate check value is an date string.

func IsDirPath

func IsDirPath(path string) bool

IsDirPath path is a local dir path

func IsEmail

func IsEmail(s string) bool

IsEmail check

func IsEmpty

func IsEmpty(val any) bool

IsEmpty of the value

func IsEqual

func IsEqual(val, wantVal any) bool

IsEqual check two value is equals.

Support:

bool, int(X), uint(X), string, float(X) AND slice, array, map

func IsFilePath

func IsFilePath(path string) bool

IsFilePath path is a local filepath

func IsFloat

func IsFloat(val any) bool

IsFloat check. allow: floatX, string

func IsFullURL

func IsFullURL(s string) bool

IsFullURL string.

func IsHexColor

func IsHexColor(s string) bool

IsHexColor string.

func IsHexadecimal

func IsHexadecimal(s string) bool

IsHexadecimal string.

func IsIP

func IsIP(s string) bool

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

func IsIPv4

func IsIPv4(s string) bool

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

func IsIPv6

func IsIPv6(s string) bool

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

func IsISBN10

func IsISBN10(s string) bool

IsISBN10 string.

func IsISBN13

func IsISBN13(s string) bool

IsISBN13 string.

func IsInt

func IsInt(val any, minAndMax ...int64) (ok bool)

IsInt check, and support length check

func IsIntString

func IsIntString(s string) bool

IsIntString check. eg "10"

func IsInts

func IsInts(val any) bool

IsInts is int slice check

func IsJSON

func IsJSON(s string) bool

Modified Customization: use custom JSON Unmarshal to handle all unmarshalling errors. IsJSON check if the string is valid JSON (note: uses json.Unmarshal).

func IsLatitude

func IsLatitude(s string) bool

IsLatitude string.

func IsLongitude

func IsLongitude(s string) bool

IsLongitude string.

func IsMAC

func IsMAC(s string) bool

IsMAC is the validation function for validating if the field's value is a valid MAC address.

func IsMap

func IsMap(val any) (ok bool)

IsMap check

func IsMultiByte

func IsMultiByte(s string) bool

IsMultiByte string.

func IsNilObj

func IsNilObj(val any) bool

IsNilObj check value is internal NilObject

func IsNumber

func IsNumber(v any) bool

IsNumber string. should >= 0

func IsNumeric

func IsNumeric(v any) bool

IsNumeric is string/int number. should >= 0

func IsPrintableASCII

func IsPrintableASCII(s string) bool

IsPrintableASCII string.

func IsRGBColor

func IsRGBColor(s string) bool

IsRGBColor string.

func IsSlice

func IsSlice(val any) (ok bool)

IsSlice check value is slice type

func IsString

func IsString(val any, minAndMaxLen ...int) (ok bool)

IsString check and support length check.

Usage:

ok := IsString(val)
ok := IsString(val, 5) // with min len check
ok := IsString(val, 5, 12) // with min and max len check

func IsStringNumber

func IsStringNumber(s string) bool

IsStringNumber is string number. should >= 0

func IsStrings

func IsStrings(val any) (ok bool)

IsStrings is string slice check

func IsURL

func IsURL(s string) bool

IsURL string.

func IsUUID

func IsUUID(s string) bool

IsUUID string

func IsUUID3

func IsUUID3(s string) bool

IsUUID3 string

func IsUUID4

func IsUUID4(s string) bool

IsUUID4 string

func IsUUID5

func IsUUID5(s string) bool

IsUUID5 string

func IsUint

func IsUint(val any) bool

IsUint check, allow: intX, uintX, string

func IsUnixPath

func IsUnixPath(s string) bool

IsUnixPath string

func IsWinPath

func IsWinPath(s string) bool

IsWinPath string

func IsZero

func IsZero(v reflect.Value) bool

IsZero reports whether v is the zero value for its type. It panics if the argument is invalid.

NOTICE: this built-in method in reflect/value.go since go 1.13

func Length

func Length(val any, wantLen int) bool

Length equal check for string, array, slice, map

func Lt

func Lt(val, max any) bool

Lt less than dst value. only check for: int(X), uint(X), float(X).

func Lte

func Lte(val, max any) bool

Lte less than or equal dst value. only check for: int(X), uint(X), float(X).

func Max

func Max(val, max any) bool

Max less than or equal dst value, alias Lte() only check for: int(X), uint(X), float(X).

func MaxLength

func MaxLength(val any, maxLen int) bool

MaxLength check for string, array, slice, map

func Min

func Min(val, min any) bool

Min check value greater or equal dst value, alias Gte() only check for: int(X), uint(X), float(X), string.

func MinLength

func MinLength(val any, minLen int) bool

MinLength check for string, array, slice, map

func NotContains

func NotContains(s, sub any) bool

NotContains check that the specified string, list(array, slice) or map does NOT contain the specified substring or element.

Notice: list check value exist. map check key exist.

func NotEqual

func NotEqual(val, wantVal any) bool

NotEqual check

func NotIn

func NotIn(val, enum any) bool

NotIn value should be not in the given enum(strings, ints, uints).

func PathExists

func PathExists(path string) bool

PathExists reports whether the named file or directory exists.

func Regexp

func Regexp(str string, pattern string) bool

Regexp match value string

func ResetOption

func ResetOption()

ResetOption reset global option

func RuneLength

func RuneLength(val any, minLen int, maxLen ...int) bool

RuneLength check string's length (including multibyte strings)

func SetBuiltinMessages

func SetBuiltinMessages(mp map[string]string)

SetBuiltinMessages override set builtin messages

func StartsWith

func StartsWith(s, sub string) bool

StartsWith check string is starts with sub-string

func StringContains

func StringContains(s, sub string) bool

StringContains check string is contains sub-string

func StringLength

func StringLength(val any, minLen int, maxLen ...int) bool

StringLength check string's length (including multibyte strings)

func Val

func Val(val any, rule string) error

Val quick validating the value by given rule. returns error on fail, return nil on check ok.

Usage:

validate.Val("xyz@mail.com", "required|email")

refer the Validation.StringRule() for parse rule string.

func ValidatorName

func ValidatorName(name string) string

ValidatorName get real validator name.

func Validators

func Validators() map[string]int8

Validators get all validator names

func ValueIsEmpty

func ValueIsEmpty(v reflect.Value) bool

ValueIsEmpty check. alias of reflects.IsEmpty()

func ValueLen

func ValueLen(v reflect.Value) int

ValueLen get value length. Deprecated: please use reflects.Len()

func Var

func Var(val any, rule string) error

Var validating the value by given rule. alias of the Val()

Types

type ConfigValidationFace

type ConfigValidationFace interface {
	ConfigValidation(v *Validation)
}

ConfigValidationFace definition. you can do something on create Validation.

type CustomMessagesFace

type CustomMessagesFace interface {
	Messages() map[string]string
}

CustomMessagesFace definition. you can custom validator error messages. Usage:

type User struct {
	Name string `json:"name" validate:"required|minLen:5"`
}

func (u *User) Messages() map[string]string {
	return MS{
		"Name.required": "oh! User name is required",
	}
}

type DataFace

type DataFace interface {
	Type() uint8
	Src() any
	Get(key string) (val any, exist bool)
	// TryGet value by key.
	// if source data is struct, will return zero check
	TryGet(key string) (val any, exist, zero bool)
	Set(field string, val any) (any, error)
	// Create validation instance create func
	Create(err ...error) *Validation
	Validation(err ...error) *Validation
}

DataFace data source interface definition

Current has three data source:

  • map
  • form
  • struct

func FromRequest

func FromRequest(r *http.Request, maxMemoryLimit ...int64) (DataFace, error)

FromRequest collect data from request instance

type Errors

type Errors map[string]MS

Errors validate errors definition

Example:

{
	"field": {validator: message, validator1: message1}
}

func (Errors) Add

func (es Errors) Add(field, validator, message string)

Add a error for the field

func (Errors) All

func (es Errors) All() map[string]map[string]string

All get all errors data

func (Errors) Empty

func (es Errors) Empty() bool

Empty no error

func (Errors) ErrOrNil

func (es Errors) ErrOrNil() error

ErrOrNil returns an random error, if no error returns nil

func (Errors) Error

func (es Errors) Error() string

Error string get

func (Errors) Field

func (es Errors) Field(field string) map[string]string

Field gets all errors for the field

func (Errors) FieldOne

func (es Errors) FieldOne(field string) string

FieldOne returns an error message for the field

func (Errors) HasField

func (es Errors) HasField(field string) bool

HasField in the errors

func (Errors) JSON

func (es Errors) JSON() []byte

JSON encode

func (Errors) One

func (es Errors) One() string

One returns an random error message text

func (Errors) OneError

func (es Errors) OneError() error

OneError returns an random error, if no error returns nil

func (Errors) Random

func (es Errors) Random() string

Random returns an random error message text

func (Errors) String

func (es Errors) String() string

String errors to string

type FieldTranslatorFace

type FieldTranslatorFace interface {
	Translates() map[string]string
}

FieldTranslatorFace definition. you can custom field translates. Usage:

type User struct {
	Name string `json:"name" validate:"required|minLen:5"`
}

func (u *User) Translates() map[string]string {
	return MS{
		"Name": "Username",
	}
}

type FilterRule

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

FilterRule definition

func (*FilterRule) AddFilters

func (r *FilterRule) AddFilters(filters ...string) *FilterRule

AddFilters add filter(s).

Usage:

r.AddFilters("int", "str2arr:,")

func (*FilterRule) Apply

func (r *FilterRule) Apply(v *Validation) (err error)

Apply rule for the rule fields

func (*FilterRule) Fields

func (r *FilterRule) Fields() []string

Fields name get

type FormData

type FormData struct {
	// Form holds any basic key-value string data
	// This includes all fields from urlencoded form,
	// and the form fields only (not files) from a multipart form
	Form url.Values
	// Files holds files from a multipart form only.
	// For any other type of request, it will always
	// be empty. Files only supports one file per key,
	// since this is by far the most common use. If you
	// need to have more than one file per key, parse the
	// files manually using r.MultipartForm.File.
	Files map[string]*multipart.FileHeader
}

FormData obtained from the request body or url query parameters or user custom setting.

func FromQuery

func FromQuery(values url.Values) *FormData

FromQuery build data instance.

Usage:

validate.FromQuery(r.URL.Query()).Create()

func FromURLValues

func FromURLValues(values url.Values) *FormData

FromURLValues build data instance.

func (*FormData) Add

func (d *FormData) Add(key string, value string)

Add adds the value to key. It appends to any existing values associated with key.

func (*FormData) AddFile

func (d *FormData) AddFile(key string, file *multipart.FileHeader)

AddFile adds the multipart form file to data with the given key.

func (*FormData) AddFiles

func (d *FormData) AddFiles(filesMap map[string][]*multipart.FileHeader)

AddFiles adds the multipart form files to data

func (*FormData) AddValues

func (d *FormData) AddValues(values url.Values)

AddValues to Data.Form

func (FormData) Bool

func (d FormData) Bool(key string) bool

Bool returns the first element in data[key] converted to a bool.

func (*FormData) Create

func (d *FormData) Create(err ...error) *Validation

Create a Validation from data

func (*FormData) Del

func (d *FormData) Del(key string)

Del deletes the values associated with key.

func (*FormData) DelFile

func (d *FormData) DelFile(key string)

DelFile deletes the file associated with key (if any). If there is no file associated with key, it does nothing.

func (*FormData) Encode

func (d *FormData) Encode() string

Encode encodes the values into “URL encoded” form ("bar=baz&foo=quux") sorted by key. Any files in d will be ignored because there is no direct way to convert a file to a URL encoded value.

func (FormData) FileBytes

func (d FormData) FileBytes(field string) ([]byte, error)

FileBytes returns the body of the file associated with key. If there is no file associated with key, it returns nil (not an error). It may return an error if there was a problem reading the file. If you need to know whether or not the file exists (i.e. whether it was provided in the request), use the FileExists method.

func (FormData) FileMimeType

func (d FormData) FileMimeType(field string) (mime string)

FileMimeType get File Mime Type name. eg "image/png"

func (FormData) Float

func (d FormData) Float(key string) float64

Float returns the first element in data[key] converted to a float.

func (FormData) Get

func (d FormData) Get(key string) (any, bool)

Get value by key

func (FormData) GetFile

func (d FormData) GetFile(key string) *multipart.FileHeader

GetFile returns the multipart form file associated with key, if any, as a *multipart.FileHeader. If there is no file associated with key, it returns nil. If you just want the body of the file, use GetFileBytes.

func (FormData) Has

func (d FormData) Has(key string) bool

Has key in the Data

func (FormData) HasField

func (d FormData) HasField(key string) bool

HasField returns true iff data.Form[key] exists. When parsing a request body, the key is considered to be in existence if it was provided in the request body, even if its value is empty.

func (FormData) HasFile

func (d FormData) HasFile(key string) bool

HasFile returns true iff data.Files[key] exists. When parsing a request body, the key is considered to be in existence if it was provided in the request body, even if the file is empty.

func (FormData) Int

func (d FormData) Int(key string) int

Int returns the first element in data[key] converted to an int.

func (FormData) Int64

func (d FormData) Int64(key string) int64

Int64 returns the first element in data[key] converted to an int64.

func (*FormData) Set

func (d *FormData) Set(field string, val any) (newVal any, err error)

Set sets the key to value. It replaces any existing values.

func (*FormData) Src

func (d *FormData) Src() any

Src data get

func (FormData) String

func (d FormData) String(key string) string

String value get by key

func (FormData) Strings

func (d FormData) Strings(key string) []string

Strings value get by key

func (FormData) TryGet

func (d FormData) TryGet(key string) (val any, exist, zero bool)

TryGet value by key

func (*FormData) Type

func (d *FormData) Type() uint8

Type get

func (*FormData) Validation

func (d *FormData) Validation(err ...error) *Validation

Validation create from data

type GlobalOption

type GlobalOption struct {
	// FilterTag name in the struct tags.
	//
	// default: filter
	FilterTag string
	// ValidateTag in the struct tags.
	//
	// default: validate
	ValidateTag string
	// FieldTag the output field name in the struct tags.
	// it as placeholder on error message.
	//
	// default: json
	FieldTag string
	// LabelTag the display name in the struct tags.
	// use for define field translate name on error.
	//
	// default: label
	LabelTag string
	// MessageTag define error message for the field.
	//
	// default: message
	MessageTag string
	// DefaultTag define default value for the field.
	//
	// tag: default TODO
	DefaultTag string
	// StopOnError If true: An error occurs, it will cease to continue to verify. default is True.
	StopOnError bool
	// SkipOnEmpty Skip check on field not exist or value is empty. default is True.
	SkipOnEmpty bool
	// UpdateSource Whether to update source field value, useful for struct validate
	UpdateSource bool
	// CheckDefault Whether to validate the default value set by the user
	CheckDefault bool
	// CheckZero Whether validate the default zero value. (intX,uintX: 0, string: "")
	CheckZero bool
	// ErrKeyFmt config. TODO
	//
	// allow:
	// - 0 use struct field name as key. (for compatible)
	// - 1 use FieldTag defined name as key.
	ErrKeyFmt int8
	// CheckSubOnParentMarked True: only collect sub-struct rule on current field has rule.
	CheckSubOnParentMarked bool
	// ValidatePrivateFields Whether to validate private fields or not, especially when inheriting other other structs.
	//
	//  type foo struct {
	//	  Field int `json:"field" validate:"required"`
	//  }
	//  type bar struct {
	//    foo // <-- validate this field
	//    Field2 int `json:"field2" validate:"required"`
	//  }
	//
	// default: false
	ValidatePrivateFields bool
}

GlobalOption settings for validate

func Option

func Option() GlobalOption

Option get global options

type M

type M map[string]any

M is short name for map[string]any

type MS

type MS map[string]string

MS is short name for map[string]string

func (MS) One

func (ms MS) One() string

One get one item's value string

func (MS) String

func (ms MS) String() string

String convert map[string]string to string

type MapData

type MapData struct {
	// Map the source map data
	Map map[string]any
	// contains filtered or unexported fields
}

MapData definition

func FromJSON

func FromJSON(s string) (*MapData, error)

FromJSON string build data instance.

func FromJSONBytes

func FromJSONBytes(bs []byte) (*MapData, error)

FromJSONBytes string build data instance.

func FromMap

func FromMap(m map[string]any) *MapData

FromMap build data instance.

func (*MapData) BindJSON

func (d *MapData) BindJSON(ptr interface{}) (int, error)

Modified Customization: use custom JSON Unmarshal to handle all unmarshalling errors. BindJSON binds v to the JSON data in the request body. It calls json.Unmarshal and sets the value of v.

func (*MapData) Create

func (d *MapData) Create(err ...error) *Validation

Create a Validation from data

func (*MapData) Get

func (d *MapData) Get(field string) (any, bool)

Get value by key. support get value by path.

func (*MapData) Set

func (d *MapData) Set(field string, val any) (any, error)

Set value by key

func (*MapData) Src

func (d *MapData) Src() any

Src get

func (*MapData) TryGet

func (d *MapData) TryGet(field string) (val any, exist, zero bool)

TryGet value by key

func (*MapData) Type

func (d *MapData) Type() uint8

Type get

func (*MapData) Validation

func (d *MapData) Validation(err ...error) *Validation

Validation create from data

type MarshalFunc

type MarshalFunc func(v interface{}) ([]byte, error)

MarshalFunc define

type NilObject

type NilObject struct{}

NilObject represent nil value for calling functions and should be reflected at custom filters as nil variable.

type Rule

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

Rule definition

func NewRule

func NewRule(fields, validator string, args ...any) *Rule

NewRule create new Rule instance

func (*Rule) Apply

func (r *Rule) Apply(v *Validation) (stop bool)

Apply current rule for the rule fields

func (*Rule) Fields

func (r *Rule) Fields() []string

Fields field names list

func (*Rule) SetBeforeFunc

func (r *Rule) SetBeforeFunc(fn func(v *Validation) bool)

SetBeforeFunc for the rule. will call it before validate.

func (*Rule) SetCheckFunc

func (r *Rule) SetCheckFunc(checkFunc any) *Rule

SetCheckFunc set custom validate func.

func (*Rule) SetFilterFunc

func (r *Rule) SetFilterFunc(fn func(val any) (any, error)) *Rule

SetFilterFunc for the rule

func (*Rule) SetMessage

func (r *Rule) SetMessage(errMsg string) *Rule

SetMessage set error message.

Usage:

v.AddRule("name", "required").SetMessage("error message")

func (*Rule) SetMessages

func (r *Rule) SetMessages(msgMap MS) *Rule

SetMessages set error message map.

Usage:

v.AddRule("name,email", "required").SetMessages(MS{
	"name": "error message 1",
	"email": "error message 2",
})

func (*Rule) SetOptional

func (r *Rule) SetOptional(optional bool)

SetOptional only validate on value is not empty.

func (*Rule) SetScene

func (r *Rule) SetScene(scene string) *Rule

SetScene name for the rule.

func (*Rule) SetSkipEmpty

func (r *Rule) SetSkipEmpty(skipEmpty bool)

SetSkipEmpty skip validate not exist field/empty value

type Rules

type Rules []*Rule

Rules definition

type SValues

type SValues map[string][]string

SValues simple values

type StructData

type StructData struct {

	// TODO field reflect values cache
	// fieldRftValues map[string]any
	// FilterTag name in the struct tags.
	//
	// see GlobalOption.FilterTag
	FilterTag string
	// ValidateTag name in the struct tags.
	//
	// see GlobalOption.ValidateTag
	ValidateTag string
	// contains filtered or unexported fields
}

StructData definition.

more struct tags define please see GlobalOption

func FromStruct

func FromStruct(s any) (*StructData, error)

FromStruct create a Data from struct

func (*StructData) Create

func (d *StructData) Create(err ...error) *Validation

Create from the StructData

func (*StructData) FuncValue

func (d *StructData) FuncValue(name string) (reflect.Value, bool)

FuncValue get func value in the src struct

func (*StructData) Get

func (d *StructData) Get(field string) (val any, exist bool)

Get value by field name. support get sub-value by path.

func (*StructData) HasField

func (d *StructData) HasField(field string) bool

HasField in the src struct

func (*StructData) Set

func (d *StructData) Set(field string, val any) (newVal any, err error)

Set value by field name.

Notice: `StructData.src` the incoming struct must be a pointer to set the value

func (*StructData) Src

func (d *StructData) Src() any

Src get

func (*StructData) TryGet

func (d *StructData) TryGet(field string) (val any, exist, zero bool)

TryGet value by field name. support get sub-value by path.

func (*StructData) Type

func (d *StructData) Type() uint8

Type get

func (*StructData) Validation

func (d *StructData) Validation(err ...error) *Validation

Validation create a Validation from the StructData

type Translator

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

Translator definition

func NewTranslator

func NewTranslator() *Translator

NewTranslator instance

func (*Translator) AddFieldMap

func (t *Translator) AddFieldMap(fieldMap map[string]string)

AddFieldMap config field output name data. If you want to display in the field with the original field is not the same

func (*Translator) AddLabelMap

func (t *Translator) AddLabelMap(fieldMap map[string]string)

AddLabelMap config field translate data map. If you want to display in the field with the original field is not the same

func (*Translator) AddMessage

func (t *Translator) AddMessage(key, msg string)

AddMessage to translator

func (*Translator) AddMessages

func (t *Translator) AddMessages(data map[string]string)

AddMessages data to translator

func (*Translator) FieldMap

func (t *Translator) FieldMap() map[string]string

FieldMap data get

func (*Translator) FieldName

func (t *Translator) FieldName(field string) string

FieldName get in the t.fieldMap

func (*Translator) HasField

func (t *Translator) HasField(field string) bool

HasField name in the t.fieldMap.

func (*Translator) HasLabel

func (t *Translator) HasLabel(field string) bool

HasLabel name in the t.labelMap

func (*Translator) HasMessage

func (t *Translator) HasMessage(key string) bool

HasMessage key in the t.messages

func (*Translator) LabelMap

func (t *Translator) LabelMap() map[string]string

LabelMap data get

func (*Translator) LabelName

func (t *Translator) LabelName(field string) string

LabelName get label name from the t.labelMap, fallback get output name from t.fieldMap

func (*Translator) LookupLabel

func (t *Translator) LookupLabel(field string) (string, bool)

LookupLabel get label name from the t.labelMap, fallback get output name from t.fieldMap. if not found, return "", false

func (*Translator) Message

func (t *Translator) Message(validator, field string, args ...any) (msg string)

Message get by validator name and field name.

func (*Translator) Reset

func (t *Translator) Reset()

Reset translator to default

type UnmarshalFunc

type UnmarshalFunc func(r *http.Request, data []byte, v interface{}) (int, error)

Modified Customization: use custom JSON Unmarshal to handle all unmarshalling errors. UnmarshalFunc define

type Validation

type Validation struct {

	// Errors for validate
	Errors Errors
	// CacheKey for cache rules
	// CacheKey string
	// StopOnError If true: An error occurs, it will cease to continue to verify
	StopOnError bool
	// SkipOnEmpty Skip check on field not exist or value is empty
	SkipOnEmpty bool
	// UpdateSource Whether to update source field value, useful for struct validate
	UpdateSource bool
	// CheckDefault Whether to validate the default value set by the user
	CheckDefault bool
	// contains filtered or unexported fields
}

Validation definition

func JSON

func JSON(s string, scene ...string) *Validation

JSON create validation from JSON string.

func Map

func Map(m map[string]any, scene ...string) *Validation

Map validation create

func New

func New(data any, scene ...string) *Validation

New create a Validation instance

data type support:

  • DataFace
  • M/map[string]any
  • SValues/url.Values/map[string][]string
  • struct ptr

func NewEmpty

func NewEmpty(scene ...string) *Validation

NewEmpty new validation instance, but not with data.

func NewValidation

func NewValidation(data DataFace, scene ...string) *Validation

NewValidation new validation instance

func Request

func Request(r *http.Request) *Validation

Request validation create

func Struct

func Struct(s any, scene ...string) *Validation

Struct validation create

func (*Validation) AddError

func (v *Validation) AddError(field, validator, msg string)

AddError message for a field

func (*Validation) AddErrorf

func (v *Validation) AddErrorf(field, msgFormat string, args ...any)

AddErrorf add a formatted error message

func (*Validation) AddFilter

func (v *Validation) AddFilter(name string, filterFunc any)

AddFilter to the Validation.

func (*Validation) AddFilters

func (v *Validation) AddFilters(m map[string]any)

AddFilters to the Validation

func (*Validation) AddMessages

func (v *Validation) AddMessages(m map[string]string)

AddMessages settings data. like WithMessages()

func (*Validation) AddRule

func (v *Validation) AddRule(fields, validator string, args ...any) *Rule

AddRule for current validation

func (*Validation) AddTranslates

func (v *Validation) AddTranslates(m map[string]string)

AddTranslates settings data. like WithTranslates()

func (*Validation) AddValidator

func (v *Validation) AddValidator(name string, checkFunc any) *Validation

AddValidator to the Validation instance. checkFunc must return a bool.

Usage:

v.AddValidator("myFunc", func(val any) bool {
	// do validate val ...
	return true
})

func (*Validation) AddValidators

func (v *Validation) AddValidators(m map[string]any) *Validation

AddValidators to the Validation instance.

func (*Validation) AppendRule

func (v *Validation) AppendRule(rule *Rule) *Rule

AppendRule instance

func (*Validation) AppendRules

func (v *Validation) AppendRules(rules ...*Rule) *Validation

AppendRules instances at once

func (*Validation) AtScene

func (v *Validation) AtScene(scene string) *Validation

AtScene setting current validate scene.

func (*Validation) BindSafeData

func (v *Validation) BindSafeData(ptr interface{}) (int, error)
	return Unmarshal(bts, ptr)
}

Modified Customization: use custom JSON Unmarshal to handle all unmarshalling errors. BindSafeData binding safe data to an struct.

func (*Validation) ConfigRules

func (v *Validation) ConfigRules(mp MS) *Validation

ConfigRules add multi rules by string map. alias of StringRules()

Usage:

v.ConfigRules(map[string]string{
	"name": "required|string|min:12",
	"age": "required|int|min:12",
})

func (*Validation) EqField

func (v *Validation) EqField(val any, dstField string) bool

EqField value should EQ the dst field value

func (*Validation) FilterFuncValue

func (v *Validation) FilterFuncValue(name string) reflect.Value

FilterFuncValue get filter by name

func (*Validation) FilterRule

func (v *Validation) FilterRule(field string, rule string) *FilterRule

FilterRule add filter rule.

Usage:

v.FilterRule("name", "trim|lower")
v.FilterRule("age", "int")

func (*Validation) FilterRules

func (v *Validation) FilterRules(rules map[string]string) *Validation

FilterRules add multi filter rules.

func (*Validation) Filtered

func (v *Validation) Filtered(key string) any

Filtered get filtered value by key

func (*Validation) FilteredData

func (v *Validation) FilteredData() M

FilteredData return filtered data.

func (*Validation) Filtering

func (v *Validation) Filtering() bool

Filtering data by filter rules

func (*Validation) Get

func (v *Validation) Get(key string) (val any, exist bool)

Get value by key.

func (*Validation) GetDefValue

func (v *Validation) GetDefValue(field string) (any, bool)

GetDefValue get default value of the field

func (*Validation) GetSafe

func (v *Validation) GetSafe(key string) any

GetSafe get safe value by key

func (*Validation) GetWithDefault

func (v *Validation) GetWithDefault(key string) (val any, exist, isDefault bool)

GetWithDefault get field value by key.

On not found, if it has default value, will return default-value.

func (*Validation) GtField

func (v *Validation) GtField(val any, dstField string) bool

GtField value should GT the dst field value

func (*Validation) GteField

func (v *Validation) GteField(val any, dstField string) bool

GteField value should GTE the dst field value

func (*Validation) HasValidator

func (v *Validation) HasValidator(name string) bool

HasValidator check

func (*Validation) InMimeTypes

func (v *Validation) InMimeTypes(fd *FormData, field, mimeType string, moreTypes ...string) bool

InMimeTypes check field is uploaded file and mime type is in the mimeTypes. Usage:

v.AddRule("video", "mimeTypes", "video/avi", "video/mpeg", "video/quicktime")

func (*Validation) InScene

func (v *Validation) InScene(scene string) *Validation

InScene alias of the AtScene()

func (*Validation) IsFail

func (v *Validation) IsFail() bool

IsFail for the validating

func (*Validation) IsFormFile

func (v *Validation) IsFormFile(fd *FormData, field string) (ok bool)

IsFormFile check field is uploaded file

func (*Validation) IsFormImage

func (v *Validation) IsFormImage(fd *FormData, field string, exts ...string) (ok bool)

IsFormImage check field is uploaded image file. Usage:

v.AddRule("avatar", "image")
v.AddRule("avatar", "image", "jpg", "png", "gif") // set ext limit

func (*Validation) IsOK

func (v *Validation) IsOK() bool

IsOK for the validating

func (*Validation) IsSuccess

func (v *Validation) IsSuccess() bool

IsSuccess for the validating

func (*Validation) LtField

func (v *Validation) LtField(val any, dstField string) bool

LtField value should LT the dst field value

func (*Validation) LteField

func (v *Validation) LteField(val any, dstField string) bool

LteField value should LTE the dst field value(for int, string)

func (*Validation) NeField

func (v *Validation) NeField(val any, dstField string) bool

NeField value should not equal the dst field value

func (*Validation) Raw

func (v *Validation) Raw(key string) (any, bool)

Raw value get by key

func (*Validation) RawVal

func (v *Validation) RawVal(key string) any

RawVal value get by key

func (*Validation) Required

func (v *Validation) Required(field string, val any) bool

Required field val check

func (*Validation) RequiredIf

func (v *Validation) RequiredIf(_ string, val any, kvs ...string) bool

RequiredIf field under validation must be present and not empty, if the anotherField field is equal to any value.

func (*Validation) RequiredUnless

func (v *Validation) RequiredUnless(_ string, val any, kvs ...string) bool

RequiredUnless field under validation must be present and not empty unless the anotherField field is equal to any value.

func (*Validation) RequiredWith

func (v *Validation) RequiredWith(_ string, val any, kvs ...string) bool

RequiredWith field under validation must be present and not empty only if any of the other specified fields are present.

func (*Validation) RequiredWithAll

func (v *Validation) RequiredWithAll(_ string, val any, kvs ...string) bool

RequiredWithAll field under validation must be present and not empty only if all of the other specified fields are present.

func (*Validation) RequiredWithout

func (v *Validation) RequiredWithout(_ string, val any, kvs ...string) bool

RequiredWithout field under validation must be present and not empty only when any of the other specified fields are not present.

func (*Validation) RequiredWithoutAll

func (v *Validation) RequiredWithoutAll(_ string, val any, kvs ...string) bool

RequiredWithoutAll field under validation must be present and not empty only when any of the other specified fields are not present.

func (*Validation) Reset

func (v *Validation) Reset()

Reset the Validation instance.

Will resets:

  • validate result
  • validate rules
  • validate filterRules
  • custom validators TODO

func (*Validation) ResetResult

func (v *Validation) ResetResult()

ResetResult reset the validate result.

func (*Validation) Safe

func (v *Validation) Safe(key string) (val any, ok bool)

Safe get safe value by key

func (*Validation) SafeData

func (v *Validation) SafeData() M

SafeData get all validated safe data

func (*Validation) SafeVal

func (v *Validation) SafeVal(key string) any

SafeVal get safe value by key

func (*Validation) Sanitize

func (v *Validation) Sanitize() bool

Sanitize data by filter rules

func (*Validation) Scene

func (v *Validation) Scene() string

Scene name get for current validation

func (*Validation) SceneFields

func (v *Validation) SceneFields() []string

SceneFields field names get

func (*Validation) Set

func (v *Validation) Set(field string, val any) error

Set value by key

func (*Validation) SetDefValue

func (v *Validation) SetDefValue(field string, val any)

SetDefValue set a default value of given field

func (*Validation) SetScene

func (v *Validation) SetScene(scene ...string) *Validation

SetScene alias of the AtScene()

func (*Validation) StringRule

func (v *Validation) StringRule(field, rule string, filterRule ...string) *Validation

StringRule add field rules by string

Usage:

v.StringRule("name", "required|string|minLen:6")
// will try convert to int before applying validation.
v.StringRule("age", "required|int|min:12", "toInt")

func (*Validation) StringRules

func (v *Validation) StringRules(mp MS) *Validation

StringRules add multi rules by string map.

Usage:

v.StringRules(map[string]string{
	"name": "required|string|min_len:12",
	"age": "required|int|min:12",
})

func (*Validation) Trans

func (v *Validation) Trans() *Translator

Trans get translator

func (*Validation) Validate

func (v *Validation) Validate(scene ...string) bool

Validate processing

func (*Validation) ValidateData

func (v *Validation) ValidateData(data DataFace) bool

ValidateData validate given data-source

func (*Validation) ValidateE

func (v *Validation) ValidateE(scene ...string) Errors

ValidateE do validate processing and return Errors

NOTE: need use len() to check the return is empty or not.

func (*Validation) ValidateErr

func (v *Validation) ValidateErr(scene ...string) error

ValidateErr do validate processing and return error

func (*Validation) Validators

func (v *Validation) Validators(withGlobal bool) map[string]int8

Validators get all validator names

func (*Validation) WithError

func (v *Validation) WithError(err error) *Validation

WithError add error of the validation

func (*Validation) WithMessages

func (v *Validation) WithMessages(m map[string]string) *Validation

WithMessages settings. you can custom validator error messages.

Usage:

	// key is "validator" or "field.validator"
	v.WithMessages(map[string]string{
		"require": "oh! {field} is required",
		"range": "oh! {field} must be in the range %d - %d",
 })

func (*Validation) WithScenarios

func (v *Validation) WithScenarios(scenes SValues) *Validation

WithScenarios is alias of the WithScenes()

func (*Validation) WithScenes

func (v *Validation) WithScenes(scenes map[string][]string) *Validation

WithScenes set scene config.

Usage:

v.WithScenes(SValues{
	"create": []string{"name", "email"},
	"update": []string{"name"},
})
ok := v.AtScene("create").Validate()

func (*Validation) WithSelf

func (v *Validation) WithSelf(fn func(v *Validation)) *Validation

WithSelf config the Validation instance. TODO rename to WithConfig

func (*Validation) WithTrans

func (v *Validation) WithTrans(trans *Translator) *Validation

WithTrans with a custom translator

func (*Validation) WithTranslates

func (v *Validation) WithTranslates(m map[string]string) *Validation

WithTranslates settings. you can be custom field translates.

Usage:

	v.WithTranslates(map[string]string{
		"name": "Username",
		"pwd": "Password",
 })

Jump to

Keyboard shortcuts

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