validator

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

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

Go to latest
Published: Jun 30, 2025 License: MIT Imports: 15 Imported by: 0

README

go-validator

CI Status Go Report Card GoDoc Code Coverage

A package of validators and sanitizers for strings, structs and collections.

features:

  • Customizable Attributes.
  • Customizable error messages.
  • Support i18n messages

Installation

Make sure that Go is installed on your computer. Type the following command in your terminal:

go get github.com/syssam/go-validator

Usage and documentation

Examples:

Available Validation Rules

  • omitempty
  • required
  • requiredIf
  • requiredUnless
  • requiredWith
  • requiredWithAll
  • requiredWithout
  • requiredWithoutAll
  • between
  • digitsBetween
  • size
  • max
  • min
  • same
  • gt
  • gte
  • lt
  • lte
  • distinct
  • email
  • alpha
  • alphaNum
  • alphaDash
  • alphaUnicode
  • alphaNumUnicode
  • alphaDashUnicode
  • numeric
  • int
  • integer
  • float
  • null
  • ip
  • ipv4
  • ipv6
  • uuid3
  • uuid4
  • uuid5
  • uuid

omitempty

The "omitempty" option specifies that the field should be omitted from the encoding if the field has an empty value, defined as false, 0, a nil pointer, a nil interface value, and any empty array, slice, map, or string.

required

The field under validation must be present in the input data and not empty. A field is considered "empty" if one of the following conditions are true:

  • The value is nil.
  • The value is an empty string.
  • The value is an empty array | map

requiredIf=anotherfield|value|...

The field under validation must be present and not empty if the anotherfield field is equal to any value.

requiredUnless=anotherfield|value|...

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

requiredWith=anotherfield|anotherfield|...

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

requiredWithAll=anotherfield|anotherfield|...

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

requiredWithout=anotherfield|anotherfield|...

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

requiredWithoutAll=anotherfield|anotherfield|...

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

between=min|max

The field under validation must have a size between the given min and max. String, Number, Array, Map are evaluated in the same fashion as the size rule.

digitsBetween=min|max

The field under validation must have a length between the given min and max.

size=value

The field under validation must have a size matching the given value. For string data, value corresponds to the number of characters. For numeric data, value corresponds to a given integer value. For an array | map | slice, size corresponds to the count of the array | map | slice.

max=value

The field under validation must be less than or equal to a maximum value. String, Number, Array, Map are evaluated in the same fashion as the size rule.

min=value

The field under validation must be greater than or equal to a minimum value. String, Number, Array, Map are evaluated in the same fashion as the size rule.

same=anotherfield

The given field must match the field under validation.

gt=anotherfield

The field under validation must be greater than the given field. The two fields must be of the same type. String, Number, Array, Map are evaluated using the same conventions as the size rule.

gte=anotherfield

The field under validation must be greater than or equal to the given field. The two fields must be of the same type. String, Number, Array, Map are evaluated using the same conventions as the size rule.

lt=anotherfield

The field under validation must be less than the given field. The two fields must be of the same type. String, Number, Array, Map are evaluated using the same conventions as the size rule.

lte=anotherfield

The field under validation must be less than or equal to the given field. The two fields must be of the same type. String, Number, Array, Map are evaluated using the same conventions as the size rule.

distinct

The field under validation must not have any duplicate values.

email

The field under validation must be formatted as an e-mail address.

alpha

The field under validation may be only contains letters. Empty string is valid.

alphaNum

The field under validation may be only contains letters and numbers. Empty string is valid.

alphaDash

The field under validation may be only contains letters, numbers, dashes and underscores. Empty string is valid.

alphaUnicode

The field under validation may be only contains letters. Empty string is valid.

alphaNumUnicode

The field under validation may be only contains letters and numbers. Empty string is valid.

alphaDashUnicode

The field under validation may be only contains letters, numbers, dashes and underscores. Empty string is valid.

numeric

The field under validation must be numbers. Empty string is valid.

int

The field under validation must be int. Empty string is valid.

float

The field under validation must be float. Empty string is valid.

ip

The field under validation must be an IP address.

ipv4

The field under validation must be an IPv4 address.

ipv6

The field under validation must be an IPv6 address.

uuid3

The field under validation must be an uuid3.

uuid4

The field under validation must be an uuid4.

uuid5

The field under validation must be an uuid5.

uuid

The field under validation must be an uuid.

Custom Validation Rules

  validator.CustomTypeTagMap.Set("customValidator", func CustomValidator(v reflect.Value, o reflect.Value, validTag *validator.ValidTag) bool {
    return false
  })
  

List of functions:

    IsNumeric(str string) bool
    IsInt(str string) bool
    IsFloat(str string) bool
    IsNull(str string) bool
    ValidateBetween(i interface{}, params []string) (bool, error)
    ValidateDigitsBetween(i interface{}, params []string) (bool, error)
    ValidateDigitsBetweenInt64(value, left, right int64) bool
    ValidateDigitsBetweenFloat64(value, left, right float64) bool
    ValidateGt(i interface{}, a interface{}) (bool, error)
    ValidateGtFloat64(v, param float64) bool
    ValidateGte(i interface{}, a interface{}) (bool, error)
    ValidateGteFloat64(v, param float64) bool
    ValidateLt(i interface{}, a interface{}) (bool, error)
    ValidateLtFloat64(v, param float64) bool
    ValidateLte(i interface{}, a interface{}) (bool, error)
    ValidateLteFloat64(v, param float64) bool
    ValidateRequired(i interface{}) bool
    ValidateMin(i interface{}, params []string) (bool, error)
    ValidateMinFloat64(v, param float64) bool
    ValidateMax(i interface{}, params []string) (bool, error)
    ValidateMaxFloat64(v, param float64) bool
    ValidateSize(i interface{}, params []string) (bool, error)
    ValidateDistinct(i interface{}) bool
    ValidateEmail(str string) bool
    ValidateAlpha(str string) bool
    ValidateAlphaNum(str string) bool
    ValidateAlphaDash(str string) bool
    ValidateAlphaUnicode(str string) bool
    ValidateAlphaNumUnicode(str string) bool
    ValidateAlphaDashUnicode(str string) bool
    ValidateIP(str string) bool
    ValidateIPv4(str string) bool
    ValidateIPv6(str string) bool
    ValidateUUID3(str string) bool
    ValidateUUID4(str string) bool
    ValidateUUID5(str string) bool
    ValidateUUID(str string) bool
    ValidateURL(str string) bool
  

Documentation

Index

Constants

View Source
const (
	Email            string = "" /* 1208-byte string literal not displayed */
	Alpha            string = "^[a-zA-Z]+$"
	AlphaNum         string = "^[a-zA-Z0-9]+$"
	AlphaDash        string = "^[a-zA-Z_-]+$"
	AlphaUnicode     string = "^[\\p{L}]+$"
	AlphaNumUnicode  string = "^[\\p{L}\\p{M}\\p{N}]+$"
	AlphaDashUnicode string = "^[\\p{L}\\p{M}\\p{N}_-]+$"
	Numeric          string = "^\\d+$"
	Int              string = "^(?:[-+]?(?:0|[1-9][0-9]*))$"
	Float            string = "^(?:[-+]?(?:[0-9]+))?(?:\\.[0-9]*)?(?:[eE][\\+\\-]?(?:[0-9]+))?$"
	Hexadecimal      string = "^[0-9a-fA-F]+$"
	HexColor         string = "^#?([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$"
	RGBColor         string = "" /* 167-byte string literal not displayed */
	RGBAColor        string = "" /* 200-byte string literal not displayed */
	HSLColor         string = "^hsl\\(\\s*(?:0|[1-9]\\d?|[12]\\d\\d|3[0-5]\\d|360)\\s*,\\s*(?:(?:0|[1-9]\\d?|100)%)\\s*,\\s*(?:(?:0|[1-9]\\d?|100)%)\\s*\\)$"
	HSLAColor        string = "" /* 158-byte string literal not displayed */
	UUID3            string = "^[0-9a-f]{8}-[0-9a-f]{4}-3[0-9a-f]{3}-[0-9a-f]{4}-[0-9a-f]{12}$"
	UUID4            string = "^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"
	UUID5            string = "^[0-9a-f]{8}-[0-9a-f]{4}-5[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"
	UUID             string = "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$"
	CreditCard       string = "^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|3[47][0-9]{13}|3[0-9]{13}|6(?:011|5[0-9]{2})[0-9]{12})$"
	ISBN10           string = "^(?:[0-9]{9}X|[0-9]{10})$"
	ISBN13           string = "^(?:97[89][0-9]{10})$"
	IP               string = `` /* 659-byte string literal not displayed */
	URLSchema        string = `((ftp|tcp|udp|wss?|https?):\/\/)`
	URLUsername      string = `(\S+(:\S*)?@)`
	URLPath          string = `((\/|\?|#)[^\s]*)`
	URLPort          string = `(:(\d{1,5}))`
	URLIP            string = `([1-9]\d?|1\d\d|2[01]\d|22[0-3]|24\d|25[0-5])(\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])){2}(?:\.([0-9]\d?|1\d\d|2[0-4]\d|25[0-5]))`
	URLSubdomain     string = `((www\.)|([a-zA-Z0-9]+([-_\.]?[a-zA-Z0-9])*[a-zA-Z0-9]\.[a-zA-Z0-9]+))`
	URL                     = `^` + URLSchema + `?` + URLUsername + `?` + `((` + URLIP + `|(\[` + IP + `\])|(([a-zA-Z0-9]([a-zA-Z0-9-_]+)?[a-zA-Z0-9]([-\.][a-zA-Z0-9]+)*)|(` + URLSubdomain + `?))?(([a-zA-Z\x{00a1}-\x{ffff}0-9]+-?-?)*[a-zA-Z\x{00a1}-\x{ffff}0-9]+)(?:\.([a-zA-Z\x{00a1}-\x{ffff}]{1,}))?))\.?` + URLPort + `?` + URLPath + `?$`
)

Basic regular expressions for validating strings

View Source
const (
	// Unknown is unresolved OS type
	Unknown = iota
	// Win is Windows type
	Win
	// Unix is *nix OS types
	Unix
)

Used by IsFilePath func

Variables

View Source
var CustomTypeRuleMap = &customTypeRuleMap{validateFunc: make(map[string]CustomTypeValidateFunc)}

CustomTypeRuleMap is a map of functions that can be used as tags for ValidateStruct function.

View Source
var Default = New()

Default returns a instance of Validator

View Source
var MessageMap = map[string]string{
	"accepted":           "The {{.Attribute}} must be accepted.",
	"activeUrl":          "The {{.Attribute}} is not a valid URL.",
	"after":              "The {{.Attribute}} must be a date after {{.Date}}.",
	"afterOrEqual":       "The {{.Attribute}} must be a date after or equal to {{.Date}}.",
	"alpha":              "The {{.Attribute}} may only contain letters.",
	"alphaDash":          "The {{.Attribute}} may only contain letters, numbers, dashes and underscores.",
	"alphaNum":           "The {{.Attribute}} may only contain letters and numbers.",
	"array":              "The {{.Attribute}} must be an array.",
	"before":             "The {{.Attribute}} must be a date before {{.Date}}.",
	"beforeOrEqual":      "The {{.Attribute}} must be a date before or equal to {{.Date}}.",
	"between.numeric":    "The {{.Attribute}} must be between {{.Min}} and {{.Max}}.",
	"between.file":       "The {{.Attribute}} must be between {{.Min}} and {{.Max}} kilobytes.",
	"between.string":     "The {{.Attribute}} must be between {{.Min}} and {{.Max}} characters.",
	"between.array":      "The {{.Attribute}} must have between {{.Min}} and {{.Max}} items.",
	"boolean":            "The {{.Attribute}} field must be true or false.",
	"confirmed":          "The {{.Attribute}} confirmation does not match.",
	"date":               "The {{.Attribute}} is not a valid date.",
	"dateFormat":         "The {{.Attribute}} does not match the format {{.Format}}.",
	"different":          "The {{.Attribute}} and {{.Other}} must be different.",
	"digits":             "The {{.Attribute}} must be {{.Digits}} digits.",
	"digitsBetween":      "The {{.Attribute}} must be between {{.Min}} and {{.Max}} digits.",
	"dimensions":         "The {{.Attribute}} has invalid image dimensions.",
	"distinct":           "The {{.Attribute}} field has a duplicate value.",
	"email":              "The {{.Attribute}} must be a valid email address.",
	"exists":             "The selected {{.Attribute}} is invalid.",
	"file":               "The {{.Attribute}} must be a file.",
	"filled":             "The {{.Attribute}} field must have a value.",
	"gt.numeric":         "The {{.Attribute}} must be greater than {{.Value}}.",
	"gt.file":            "The {{.Attribute}} must be greater than {{.Value}} kilobytes.",
	"gt.string":          "The {{.Attribute}} must be greater than {{.Value}} characters.",
	"gt.array":           "The {{.Attribute}} must have greater than {{.Value}} items.",
	"gte.numeric":        "The {{.Attribute}} must be greater than or equal {{.Value}}.",
	"gte.file":           "The {{.Attribute}} must be greater than or equal {{.Value}} kilobytes.",
	"gte.string":         "The {{.Attribute}} must be greater than or equal {{.Value}} characters.",
	"gte.array":          "The {{.Attribute}} must have {{.Value}} items or more.",
	"image":              "The {{.Attribute}} must be an image.",
	"in":                 "The selected {{.Attribute}} is invalid.",
	"inArray":            "The {{.Attribute}} field does not exist in {{.Other}}.",
	"integer":            "The {{.Attribute}} must be an integer.",
	"ip":                 "The {{.Attribute}} must be a valid IP address.",
	"ipv4":               "The {{.Attribute}} must be a valid IPv4 address.",
	"ipv6":               "The {{.Attribute}} must be a valid IPv6 address.",
	"json":               "The {{.Attribute}} must be a valid JSON string.",
	"lt.numeric":         "The {{.Attribute}} must be less than {{.Value}}.",
	"lt.file":            "The {{.Attribute}} must be less than {{.Value}} kilobytes.",
	"lt.string":          "The {{.Attribute}} must be less than {{.Value}} characters.",
	"lt.array":           "The {{.Attribute}} must have less than {{.Value}} items.",
	"lte.numeric":        "The {{.Attribute}} must be less than or equal {{.Value}}.",
	"lte.file":           "The {{.Attribute}} must be less than or equal {{.Value}} kilobytes.",
	"lte.string":         "The {{.Attribute}} must be less than or equal {{.Value}} characters.",
	"lte.array":          "The {{.Attribute}} must not have more than {{.Value}} items.",
	"max.numeric":        "The {{.Attribute}} may not be greater than {{.Max}}.",
	"max.file":           "The {{.Attribute}} may not be greater than {{.Max}} kilobytes.",
	"max.string":         "The {{.Attribute}} may not be greater than {{.Max}} characters.",
	"max.array":          "The {{.Attribute}} may not have more than {{.Max}} items.",
	"mimes":              "The {{.Attribute}} must be a file of type: {{.Values}}.",
	"mimetypes":          "The {{.Attribute}} must be a file of type: {{.Values}}.",
	"min.numeric":        "The {{.Attribute}} must be at least {{.Min}}.",
	"min.file":           "The {{.Attribute}} must be at least {{.Min}} kilobytes.",
	"min.string":         "The {{.Attribute}} must be at least {{.Min}} characters.",
	"min.array":          "The {{.Attribute}} must have at least {{.Min}} items.",
	"notIn":              "The selected {{.Attribute}} is invalid.",
	"notRegex":           "The {{.Attribute}} format is invalid.",
	"numeric":            "The {{.Attribute}} must be a number.",
	"present":            "The {{.Attribute}} field must be present.",
	"regex":              "The {{.Attribute}} format is invalid.",
	"required":           "The {{.Attribute}} field is required.",
	"requiredIf":         "The {{.Attribute}} field is required when {{.Other}} is {{.Value}}.",
	"requiredUnless":     "The {{.Attribute}} field is required unless {{.Other}} is in {{.Values}}.",
	"requiredWith":       "The {{.Attribute}} field is required when {{.Values}} is present.",
	"requiredWithAll":    "The {{.Attribute}} field is required when {{.Values}} is present.",
	"requiredWithout":    "The {{.Attribute}} field is required when {{.Values}} is not present.",
	"requiredWithoutAll": "The {{.Attribute}} field is required when none of {{.Values}} are present.",
	"same":               "The {{.Attribute}} and {{.Other}} must match.",
	"size.numeric":       "The {{.Attribute}} must be {{.Size}}.",
	"size.file":          "The {{.Attribute}} must be {{.Size}} kilobytes.",
	"size.string":        "The {{.Attribute}} must be {{.Size}} characters.",
	"size.array":         "The {{.Attribute}} must contain {{.Size}} items.",
	"string":             "The {{.Attribute}} must be a string.",
	"timezone":           "The {{.Attribute}} must be a valid zone.",
	"unique":             "The {{.Attribute}} has already been taken.",
	"uploaded":           "The {{.Attribute}} failed to upload.",
	"uuid3":              "The {{.Attribute}} format is invalid.",
	"uuid4":              "The {{.Attribute}} format is invalid.",
	"uuid5":              "The {{.Attribute}} format is invalid.",
	"uuid":               "The {{.Attribute}} format is invalid.",
}

MessageMap is a map of string, that can be used as error message for ValidateStruct function.

View Source
var Mimes = map[string]string{}/* 767 elements not displayed */

Mimes is a map of extension to MIME types.

View Source
var ParamRuleMap = map[string]ParamValidateFunc{
	"between":       validateBetween,
	"digitsBetween": validateDigitsBetween,
	"min":           validateMin,
	"max":           validateMax,
	"size":          validateSize,
	"gt":            validateGtParam,
	"gte":           validateGteParam,
	"lt":            validateLtParam,
	"lte":           validateLteParam,
}

ParamRuleMap is a map of functions, that can be used as tags for ValidateStruct function.

View Source
var RuleMap = map[string]ValidateFunc{
	"distinct": validateDistinct,
}

RuleMap is a map of functions, that can be used as tags for ValidateStruct function.

View Source
var StringRulesMap = map[string]StringValidateFunc{
	"numeric":          IsNumeric,
	"int":              IsInt,
	"integer":          IsInt,
	"float":            IsFloat,
	"email":            ValidateEmail,
	"alpha":            ValidateAlpha,
	"alphaNum":         ValidateAlphaNum,
	"alphaDash":        ValidateAlphaDash,
	"alphaUnicode":     ValidateAlphaUnicode,
	"alphaNumUnicode":  ValidateAlphaNumUnicode,
	"alphaDashUnicode": ValidateAlphaDashUnicode,
	"ip":               ValidateIP,
	"ipv4":             ValidateIPv4,
	"ipv6":             ValidateIPv6,
	"uuid3":            ValidateUUID3,
	"uuid4":            ValidateUUID4,
	"uuid5":            ValidateUUID5,
	"uuid":             ValidateUUID,
	"url":              ValidateURL,
}

StringRulesMap is a map of functions, that can be used as tags for ValidateStruct function when reflect type is string.

Functions

func Empty

func Empty(v reflect.Value) bool

Empty determine whether a variable is empty

func InString

func InString(str string, params []string) bool

InString check if string str is a member of the set of strings params

func IsEmptyString

func IsEmptyString(str string) bool

IsEmptyString check if the string is empty.

func IsFloat

func IsFloat(str string) bool

IsFloat check if the string must be an float. Empty string is valid.

func IsInt

func IsInt(str string) bool

IsInt check if the string must be an integer. Empty string is valid.

func IsNull

func IsNull(str string) bool

IsNull check if the string is null.

func IsNumeric

func IsNumeric(str string) bool

IsNumeric check if the string must be numeric. Empty string is valid.

func ToBool

func ToBool(str string) bool

ToBool convert the input string to a bool if the input is not a string.

func ToFloat

func ToFloat(str string) (float64, error)

ToFloat convert the input string to a float, or 0.0 if the input is not a float.

func ToInt

func ToInt(value interface{}) (res int64, err error)

ToInt convert the input string or any int type to an integer type 64, or 0 if the input is not an integer.

func ToString

func ToString(obj interface{}) string

ToString convert the input to a string with optimized fast paths.

func ToUint

func ToUint(param string) (res uint64, err error)

ToUint convert the input string if the input is not an unit.

func ValidateAlpha

func ValidateAlpha(str string) bool

ValidateAlpha check if the string may be only contains letters (a-zA-Z). Empty string is valid.

func ValidateAlphaDash

func ValidateAlphaDash(str string) bool

ValidateAlphaDash check if the string may be only contains letters, numbers, dashes and underscores. Empty string is valid.

func ValidateAlphaDashUnicode

func ValidateAlphaDashUnicode(str string) bool

ValidateAlphaDashUnicode check if the string may be only contains letters, numbers, dashes and underscores. Empty string is valid.

func ValidateAlphaNum

func ValidateAlphaNum(str string) bool

ValidateAlphaNum check if the string may be only contains letters and numbers. Empty string is valid.

func ValidateAlphaNumUnicode

func ValidateAlphaNumUnicode(str string) bool

ValidateAlphaNumUnicode check if the string may be only contains letters and numbers. Empty string is valid.

func ValidateAlphaUnicode

func ValidateAlphaUnicode(str string) bool

ValidateAlphaUnicode check if the string may be only contains letters (a-zA-Z). Empty string is valid.

func ValidateBetween

func ValidateBetween(i interface{}, params []string) (bool, error)

ValidateBetween check The field under validation must have a size between the given min and max. Strings, numerics, arrays, and files are evaluated in the same fashion as the size rule.

func ValidateBetweenString

func ValidateBetweenString(v string, left, right int64) bool

ValidateBetweenString is

func ValidateDigitsBetween

func ValidateDigitsBetween(i interface{}, params []string) (bool, error)

ValidateDigitsBetween check The field under validation must have a length between the given min and max.

func ValidateDigitsBetweenFloat64

func ValidateDigitsBetweenFloat64(value, left, right float64) bool

ValidateDigitsBetweenFloat64 returns true if value lies between left and right border

func ValidateDigitsBetweenInt64

func ValidateDigitsBetweenInt64(value, left, right int64) bool

ValidateDigitsBetweenInt64 returns true if value lies between left and right border

func ValidateDigitsBetweenUint64

func ValidateDigitsBetweenUint64(value, left, right uint64) bool

ValidateDigitsBetweenUint64 returns true if value lies between left and right border

func ValidateDistinct

func ValidateDistinct(i interface{}) bool

ValidateDistinct is the validation function for validating an attribute is unique among other values.

func ValidateEmail

func ValidateEmail(str string) bool

ValidateEmail check if the string is an email.

func ValidateGt

func ValidateGt(i, a interface{}) (bool, error)

ValidateGt is the validation function for validating if the current field's value is greater than to the param's value.

func ValidateGtFloat64

func ValidateGtFloat64(v, param float64) bool

ValidateGtFloat64 is the validation function for validating if the current field's value is greater than to the param's value.

func ValidateGtParam

func ValidateGtParam(i interface{}, params []string) (bool, error)

ValidateGtParam is the validation function for validating if the current field's value is greater than the param's value.

func ValidateGte

func ValidateGte(i, a interface{}) (bool, error)

ValidateGte is the validation function for validating if the current field's value is greater than to the param's value.

func ValidateGteFloat64

func ValidateGteFloat64(v, param float64) bool

ValidateGteFloat64 is the validation function for validating if the current field's value is greater than or equal to the param's value.

func ValidateGteParam

func ValidateGteParam(i interface{}, params []string) (bool, error)

ValidateGteParam is the validation function for validating if the current field's value is greater than or equal to the param's value.

func ValidateIP

func ValidateIP(v string) bool

ValidateIP check if the string is an ip address.

func ValidateIPv4

func ValidateIPv4(v string) bool

ValidateIPv4 check if the string is an ipv4 address.

func ValidateIPv6

func ValidateIPv6(v string) bool

ValidateIPv6 check if the string is an ipv6 address.

func ValidateImage

func ValidateImage(data []byte) bool

ValidateImage is the validation function for the The file under validation must be an image (jpeg, png, bmp, gif, or svg)

func ValidateLt

func ValidateLt(i, a interface{}) (bool, error)

ValidateLt is the validation function for validating if the current field's value is less than the param's value.

func ValidateLtFloat64

func ValidateLtFloat64(v, param float64) bool

ValidateLtFloat64 is the validation function for validating if the current field's value is less than the param's value.

func ValidateLtParam

func ValidateLtParam(i interface{}, params []string) (bool, error)

ValidateLtParam is the validation function for validating if the current field's value is less than the param's value.

func ValidateLte

func ValidateLte(i, a interface{}) (bool, error)

ValidateLte is the validation function for validating if the current field's value is less than or equal to the param's value.

func ValidateLteFloat64

func ValidateLteFloat64(v, param float64) bool

ValidateLteFloat64 is the validation function for validating if the current field's value is less than or equal to the param's value.

func ValidateLteParam

func ValidateLteParam(i interface{}, params []string) (bool, error)

ValidateLteParam is the validation function for validating if the current field's value is less than or equal to the param's value.

func ValidateMax

func ValidateMax(i interface{}, params []string) (bool, error)

ValidateMax is the validation function for validating if the current field's value is less than or equal to the param's value.

func ValidateMaxFloat64

func ValidateMaxFloat64(v, param float64) bool

ValidateMaxFloat64 is the validation function for validating if the current field's value is less than or equal to the param's value.

func ValidateMimeTypes

func ValidateMimeTypes(data []byte, mimeTypes []string) bool

ValidateMimeTypes is the validation function for the file must match one of the given MIME types.

func ValidateMimes

func ValidateMimes(data []byte, mimes []string) (bool, error)

ValidateMimes is the validation function for the file must have a MIME type corresponding to one of the listed extensions.

func ValidateMin

func ValidateMin(i interface{}, params []string) (bool, error)

ValidateMin is the validation function for validating if the current field's value is greater than or equal to the param's value.

func ValidateMinFloat64

func ValidateMinFloat64(v, param float64) bool

ValidateMinFloat64 is the validation function for validating if the current field's value is greater than or equal to the param's value.

func ValidateRequired

func ValidateRequired(i interface{}) bool

ValidateRequired check value required when anotherField str is a member of the set of strings params

func ValidateSame

func ValidateSame(i, a interface{}) (bool, error)

ValidateSame is the validation function for validating if the current field's value is greater than or equal to the param's value.

func ValidateSize

func ValidateSize(i interface{}, params []string) (bool, error)

ValidateSize The field under validation must have a size matching the given value. For string data, value corresponds to the number of characters. For numeric data, value corresponds to a given integer value. For an array | map | slice, size corresponds to the count of the array | map | slice.

func ValidateStruct

func ValidateStruct(s interface{}) error

ValidateStruct use tags for fields. result will be equal to `false` if there are any errors.

func ValidateURL

func ValidateURL(str string) bool

ValidateURL check if the string is an URL.

func ValidateUUID

func ValidateUUID(str string) bool

ValidateUUID check if the string is an uuid.

func ValidateUUID3

func ValidateUUID3(str string) bool

ValidateUUID3 check if the string is an uuid3.

func ValidateUUID4

func ValidateUUID4(str string) bool

ValidateUUID4 check if the string is an uuid4.

func ValidateUUID5

func ValidateUUID5(str string) bool

ValidateUUID5 check if the string is an uuid5.

Types

type CustomTypeValidateFunc

type CustomTypeValidateFunc func(v reflect.Value, o reflect.Value, validTag *ValidTag) bool

CustomTypeValidateFunc is a wrapper for validator functions that returns bool. first parameter is field value second parameter is struct field third parameter is validTag message, pass the variable to the message

type ErrorResponse

type ErrorResponse struct {
	Message   string `json:"message"`
	Parameter string `json:"parameter"`
}

type Errors

type Errors []error

Errors is an array of multiple errors and conforms to the error interface.

func (Errors) Error

func (es Errors) Error() string

Error implements the error interface

func (Errors) Errors

func (es Errors) Errors() []error

Errors returns itself for compatibility

func (Errors) FieldErrors

func (es Errors) FieldErrors() []*FieldError

FieldErrors returns all FieldError instances

func (Errors) GetFieldError

func (es Errors) GetFieldError(fieldName string) *FieldError

GetFieldError returns the first error for the specified field

func (Errors) GroupByField

func (es Errors) GroupByField() map[string][]*FieldError

GroupByField groups errors by field name

func (Errors) HasFieldError

func (es Errors) HasFieldError(fieldName string) bool

HasFieldError checks if there's an error for the specified field

func (Errors) MarshalJSON

func (es Errors) MarshalJSON() ([]byte, error)

MarshalJSON output Json format.

type FieldError

type FieldError struct {
	Name              string            `json:"name"`
	StructName        string            `json:"struct_name,omitempty"`
	Tag               string            `json:"tag"`
	MessageName       string            `json:"message_name,omitempty"`
	MessageParameters MessageParameters `json:"message_parameters,omitempty"`
	Attribute         string            `json:"attribute,omitempty"`
	DefaultAttribute  string            `json:"default_attribute,omitempty"`
	Value             string            `json:"value,omitempty"`
	Message           string            `json:"message"`
	FuncError         error             `json:"func_error,omitempty"`
}

FieldError encapsulates name, message, and value etc.

func (*FieldError) Error

func (fe *FieldError) Error() string

Error returns the error message with optional function error details

func (*FieldError) HasFuncError

func (fe *FieldError) HasFuncError() bool

HasFuncError checks if there's an underlying function error

func (*FieldError) SetMessage

func (fe *FieldError) SetMessage(msg string)

SetMessage sets the user-friendly message while preserving function error

func (*FieldError) Unwrap

func (fe *FieldError) Unwrap() error

Unwrap implements the errors.Unwrap interface for error chain support

type MessageParameters

type MessageParameters []messageParameter

A MessageParameters represents store message parameter into field struct.

type ParamValidateFunc

type ParamValidateFunc func(v reflect.Value, params []string) (bool, error)

ParamValidateFunc is

type StringParamValidateFunc

type StringParamValidateFunc func(str string, params []string) bool

StringParamValidateFunc is

type StringValidateFunc

type StringValidateFunc func(str string) bool

StringValidateFunc is

type Translate

type Translate map[string]string

Translate translate type

type Translator

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

Translator type

func NewTranslator

func NewTranslator() *Translator

NewTranslator returns a new instance of 'translator' with sane defaults.

func (*Translator) LoadMessage

func (t *Translator) LoadMessage(langCode string) Translate

LoadMessage load message

func (*Translator) SetAttributes

func (t *Translator) SetAttributes(langCode string, messages Translate)

SetAttributes set attributes

func (*Translator) SetMessage

func (t *Translator) SetMessage(langCode string, messages Translate)

SetMessage set Message

func (*Translator) Trans

func (t *Translator) Trans(errors Errors, language string) Errors

Trans translate errors

type UnsupportedTypeError

type UnsupportedTypeError struct {
	Type reflect.Type
}

UnsupportedTypeError is a wrapper for reflect.Type

func (*UnsupportedTypeError) Error

func (e *UnsupportedTypeError) Error() string

Error returns string equivalent for reflect.Type

type ValidTag

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

A ValidTag represents parse validTag into field struct.

type ValidateFunc

type ValidateFunc func(v reflect.Value) (bool, error)

ValidateFunc is

type Validator

type Validator struct {
	Attributes    map[string]string
	CustomMessage map[string]string
	Translator    *Translator
}

Validator construct

func New

func New() *Validator

New returns a new instance of Validator

func (*Validator) ValidateStruct

func (v *Validator) ValidateStruct(s interface{}, jsonNamespace, structNamespace []byte) error

ValidateStruct use tags for fields. result will be equal to `false` if there are any errors.

Directories

Path Synopsis
_examples
custom command
echo command
gin command
iris command
simple command
translation command
translations command
lang
en

Jump to

Keyboard shortcuts

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