validator

package module
v1.4.0 Latest Latest
Warning

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

Go to latest
Published: Jan 4, 2026 License: MIT Imports: 18 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
  • nullable
  • 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
  • url
  • date
  • dateFormat
  • after
  • afterOrEqual
  • before
  • beforeOrEqual
  • regex
  • notRegex
  • in
  • notIn
  • boolean
  • accepted
  • declined
  • country
  • country.alpha2
  • country.alpha3
  • country.numeric
  • currency
  • currency.all
  • currency.fiat
  • currency.crypto
  • language
  • language.alpha2
  • language.alpha3
  • phone
  • phone.e164

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.

url

The field under validation must be a valid URL.

date

The field under validation must be a valid date.

dateFormat=format

The field under validation must match the given format. Example: dateFormat=2006-01-02

after=date

The field under validation must be a date after the given date. Supports relative dates.

type BookingForm struct {
    CheckIn time.Time `valid:"after=today"`
    Event   time.Time `valid:"after=tomorrow"`
    Future  time.Time `valid:"after=today+7d"`
}

Relative date keywords:

  • today - Today at midnight
  • tomorrow - Tomorrow at midnight
  • yesterday - Yesterday at midnight
  • now - Current time
  • today+7d - 7 days from today
  • today-1m - 1 month ago
  • today-18y - 18 years ago

afterOrEqual=date

The field under validation must be a date after or equal to the given date. Supports relative dates.

before=date

The field under validation must be a date before the given date. Supports relative dates.

type UserForm struct {
    BirthDate time.Time `valid:"before=today-18y"` // Must be 18 years or older
}

beforeOrEqual=date

The field under validation must be a date before or equal to the given date. Supports relative dates.

regex=pattern

The field under validation must match the given regular expression.

type Form struct {
    Code string `valid:"regex=^[A-Z]{3}-[0-9]{4}$"`
}

notRegex=pattern

The field under validation must not match the given regular expression.

in=value1|value2|...

The field under validation must be included in the given list of values.

notIn=value1|value2|...

The field under validation must not be included in the given list of values.

boolean

The field under validation must be able to be cast as a boolean. Accepted input are true, false, 1, 0, "1", "0", "true", "false", "yes", "no", "on", "off".

accepted

The field under validation must be "yes", "on", 1, or true.

declined

The field under validation must be "no", "off", 0, or false.

country, country.alpha2, country.alpha3, country.numeric

The field under validation must be a valid ISO 3166-1 country code.

  • country or country.alpha2 - 2-letter code (e.g., US, GB, CN)
  • country.alpha3 - 3-letter code (e.g., USA, GBR, CHN)
  • country.numeric - Numeric code (e.g., 840, 826, 156)
type Address struct {
    Country string `valid:"required,country.alpha2"`
}

currency, currency.fiat, currency.crypto

The field under validation must be a valid currency code.

  • currency or currency.all - Any currency (fiat + crypto)
  • currency.fiat - ISO 4217 3-letter code (e.g., USD, EUR, CNY)
  • currency.crypto - Cryptocurrency code (e.g., BTC, ETH, USDT, SOL)
type Payment struct {
    Currency   string `valid:"required,currency"`        // fiat or crypto
    FiatOnly   string `valid:"required,currency.fiat"`   // fiat only
    CryptoOnly string `valid:"required,currency.crypto"` // crypto only
}

language, language.alpha2, language.alpha3

The field under validation must be a valid ISO 639 language code.

  • language or language.alpha2 - 2-letter code (e.g., en, zh, ja)
  • language.alpha3 - 3-letter code (e.g., eng, zho, jpn)
type UserPreferences struct {
    Language string `valid:"required,language.alpha2"`
}

phone, phone.e164

The field under validation must be a valid phone number.

  • phone.e164 - E.164 format with country code (e.g., +14155551234)
  • phone - Any valid phone number format with country code
type Contact struct {
    Phone string `valid:"required,phone.e164"`
}

Type-Safe Date Validation (Alternative API)

For those who prefer type-safe validation over struct tags, you can use the fluent API:

import "github.com/syssam/go-validator"

// Using standalone functions if !validator.IsDateAfter(checkIn, validator.Today()) { return errors.New("check-in must be after today") }

// Using fluent builder rule := validator.Date("birth_date").Before(validator.T(validator.Today()).SubYears(18)) if err := rule.ValidateWithError(user.BirthDate); err != nil { return err }

// Available helper functions today := validator.Today() // Today at midnight tomorrow := validator.Tomorrow() // Tomorrow at midnight yesterday := validator.Yesterday() // Yesterday at midnight

// Date arithmetic with TimeHelper weekAgo := validator.T(validator.Today()).SubDays(7) nextMonth := validator.T(validator.Today()).AddMonths(1) years18Ago := validator.T(validator.Today()).SubYears(18)

Custom Validation Rules

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

List of functions:

String Validation

IsNumeric(str string) bool
IsInt(str string) bool
IsFloat(str string) bool
IsNull(str string) bool
IsEmail(str string) bool
IsAlpha(str string) bool
IsAlphaNum(str string) bool
IsAlphaDash(str string) bool
IsAlphaUnicode(str string) bool
IsAlphaNumUnicode(str string) bool
IsAlphaDashUnicode(str string) bool
IsIP(str string) bool
IsIPv4(str string) bool
IsIPv6(str string) bool
IsUUID3(str string) bool
IsUUID4(str string) bool
IsUUID5(str string) bool
IsUUID(str string) bool
IsURL(str string) bool

Value Validation (Reflection-based)

IsRequired(i interface{}) bool
IsBetween(i interface{}, params []string) (bool, error)
IsDigitsBetween(i interface{}, params []string) (bool, error)
IsMin(i interface{}, params []string) (bool, error)
IsMax(i interface{}, params []string) (bool, error)
IsSize(i interface{}, params []string) (bool, error)
IsDistinct(i interface{}) bool
IsGt(i interface{}, a interface{}) (bool, error)
IsGte(i interface{}, a interface{}) (bool, error)
IsLt(i interface{}, a interface{}) (bool, error)
IsLte(i interface{}, a interface{}) (bool, error)

Date Validation

Today() time.Time
Tomorrow() time.Time
Yesterday() time.Time
Now() time.Time
IsDateAfter(value, after time.Time) bool
IsDateAfterOrEqual(value, after time.Time) bool
IsDateBefore(value, before time.Time) bool
IsDateBeforeOrEqual(value, before time.Time) bool
IsDateBetween(value, start, end time.Time) bool
IsDateBetweenOrEqual(value, start, end time.Time) bool
IsToday(value time.Time) bool
IsFuture(value time.Time) bool
IsPast(value time.Time) bool

Locale Validation (Country, Currency, Language, Phone)

IsCountryCode(str string) bool
IsCountryAlpha2(str string) bool
IsCountryAlpha3(str string) bool
IsCountryNumeric(str string) bool
IsCurrencyCode(str string) bool
IsCurrencyNumeric(str string) bool
IsCurrency(str string) bool
IsLanguageCode(str string) bool
IsLanguageAlpha2(str string) bool
IsLanguageAlpha3(str string) bool
IsPhoneE164(str string) bool
IsPhone(str string, region string) bool
IsPhoneValid(str string) bool
IsPhoneMobile(str string, region string) bool
FormatPhoneE164(str string, region string) (string, error)
FormatPhoneNational(str string, region string) (string, error)
FormatPhoneInternational(str string, region string) (string, error)

Generic Validation (Go 1.18+, Type-safe)

IsGenericRequired[T comparable](value T) bool
IsGenericRequiredSlice[T any](value []T) bool
IsGenericRequiredMap[K comparable, V any](value map[K]V) bool
IsGenericMin[T NumericType](value, min T) bool
IsGenericMax[T NumericType](value, max T) bool
IsGenericBetween[T NumericType](value, min, max T) bool
IsGenericGt[T OrderedType](value, threshold T) bool
IsGenericGte[T OrderedType](value, threshold T) bool
IsGenericLt[T OrderedType](value, threshold T) bool
IsGenericLte[T OrderedType](value, threshold T) bool
IsGenericDistinct[T comparable](value []T) bool
IsGenericIn[T comparable](value T, allowed []T) bool
IsGenericNotIn[T comparable](value T, disallowed []T) bool

Documentation

Index

Constants

View Source
const (
	Email            string = `^[a-zA-Z0-9.!#$%&'*+/=?^_` + "`" + `{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$`
	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}$"
	ULID             string = "^[0-7][0-9A-HJKMNP-TV-Z]{25}$"
	ASCII            string = "^[\x00-\x7F]*$"
	MACAddress       string = "^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$|^([0-9A-Fa-f]{4}\\.){2}([0-9A-Fa-f]{4})$"
	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 Note: Email regex is simplified to prevent ReDoS attacks while maintaining practical validation

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 (
	ValidateBetween           = IsBetween
	ValidateDigitsBetween     = IsDigitsBetween
	ValidateSize              = IsSize
	ValidateMax               = IsMax
	ValidateMin               = IsMin
	ValidateGtParam           = IsGtParam
	ValidateGteParam          = IsGteParam
	ValidateLtParam           = IsLtParam
	ValidateLteParam          = IsLteParam
	ValidateSame              = IsSame
	ValidateLt                = IsLt
	ValidateLte               = IsLte
	ValidateGt                = IsGt
	ValidateGte               = IsGte
	ValidateDistinct          = IsDistinct
	ValidateMultipleOf        = IsMultipleOf
	ValidateMaxDigits         = IsMaxDigits
	ValidateMinDigits         = IsMinDigits
	ValidateDecimalPrecision  = IsDecimalPrecision
	ValidateContains          = IsContains
	ValidateDoesntContain     = IsDoesntContain
	ValidateMimeTypes         = IsMimeTypes
	ValidateMimes             = IsMimes
	ValidateImage             = IsImage
	ValidateRequired          = IsRequired
	ValidateAccepted          = IsAccepted
	ValidateDeclined          = IsDeclined
	ValidateProhibited        = IsProhibited
	ValidateMissing           = IsMissing
	ValidatePresent           = IsPresent
	ValidateRequiredArrayKeys = IsRequiredArrayKeys
	ValidateList              = IsList
	ValidateDate              = IsDate
	ValidateDateFormat        = IsDateFormat
	ValidateAfter             = IsAfter
	ValidateAfterOrEqual      = IsAfterOrEqual
	ValidateBefore            = IsBefore
	ValidateBeforeOrEqual     = IsBeforeOrEqual
	ValidateIn                = IsIn
	ValidateNotIn             = IsNotIn
	ValidateDifferent         = IsDifferent
	ValidateJSON              = IsJSON
	ValidateRegex             = IsRegex
	ValidateNotRegex          = IsNotRegex
	ValidateBoolean           = IsBoolean
	ValidateString            = IsString
	ValidateArray             = IsArray
	ValidateFilled            = IsFilled
)
View Source
var (
	DateAfter          = IsDateAfter
	DateAfterOrEqual   = IsDateAfterOrEqual
	DateBefore         = IsDateBefore
	DateBeforeOrEqual  = IsDateBeforeOrEqual
	DateBetween        = IsDateBetween
	DateBetweenOrEqual = IsDateBetweenOrEqual
)
View Source
var (
	IsDecimalRequired      = func(v decimal.Decimal) bool { return !v.IsZero() }
	IsDecimalMin           = IsDecimalGte
	IsDecimalMax           = IsDecimalLte
	ValidateDecimalMin     = IsDecimalGte
	ValidateDecimalMax     = IsDecimalLte
	ValidateDecimalGt      = IsDecimalGt
	ValidateDecimalGte     = IsDecimalGte
	ValidateDecimalLt      = IsDecimalLt
	ValidateDecimalLte     = IsDecimalLte
	ValidateDecimalZero    = IsDecimalZero
	ValidateDecimalBetween = IsDecimalBetween
)

Aliases for consistency with other validators.

View Source
var (
	ValidateDecimalPositive = IsDecimalPositive
	ValidateDecimalNegative = IsDecimalNegative
)

Deprecated aliases for backward compatibility.

View Source
var (
	IsFloat64Min = IsFloat64Gte
	IsFloat64Max = IsFloat64Lte
)

Aliases for consistency with other validators.

View Source
var (
	ValidateDigitsBetweenFloat64 = IsFloat64Between
	ValidateMaxFloat64           = IsFloat64Lte
	ValidateMinFloat64           = IsFloat64Gte
	ValidateLtFloat64            = IsFloat64Lt
	ValidateLteFloat64           = IsFloat64Lte
	ValidateGteFloat64           = IsFloat64Gte
	ValidateGtFloat64            = IsFloat64Gt
)

Deprecated: Use Is* functions instead.

View Source
var (
	IsInt64Min = IsInt64Gte
	IsInt64Max = IsInt64Lte
)

Aliases for consistency with other validators.

View Source
var (
	ValidateBetweenString    = IsStringBetween
	ValidateEmail            = IsEmail
	ValidateAlpha            = IsAlpha
	ValidateAlphaNum         = IsAlphaNum
	ValidateAlphaDash        = IsAlphaDash
	ValidateAlphaUnicode     = IsAlphaUnicode
	ValidateAlphaNumUnicode  = IsAlphaNumUnicode
	ValidateAlphaDashUnicode = IsAlphaDashUnicode
	ValidateIP               = IsIP
	ValidateIPv4             = IsIPv4
	ValidateIPv6             = IsIPv6
	ValidateUUID             = IsUUID
	ValidateUUID3            = IsUUID3
	ValidateUUID4            = IsUUID4
	ValidateUUID5            = IsUUID5
	ValidateURL              = IsURL
	ValidateHexColor         = IsHexColor
	ValidateTimezone         = IsTimezone
	ValidateASCII            = IsASCII
	ValidateLowercase        = IsLowercase
	ValidateUppercase        = IsUppercase
	ValidateStartsWith       = IsStartsWith
	ValidateEndsWith         = IsEndsWith
	ValidateDoesntStartWith  = IsDoesntStartWith
	ValidateDoesntEndWith    = IsDoesntEndWith
	ValidateMACAddress       = IsMACAddress
	ValidateULID             = IsULID
)

Deprecated: Use Is* functions instead.

View Source
var (
	IsUint64Min = IsUint64Gte
	IsUint64Max = IsUint64Lte
)

Aliases for consistency with other validators.

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{}/* 137 elements not displayed */

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":           isBetween,
	"digitsBetween":     isDigitsBetween,
	"min":               isMin,
	"max":               isMax,
	"size":              isSize,
	"gt":                isGtParam,
	"gte":               isGteParam,
	"lt":                isLtParam,
	"lte":               isLteParam,
	"multipleOf":        isMultipleOf,
	"maxDigits":         isMaxDigits,
	"minDigits":         isMinDigits,
	"decimal":           isDecimalPrecision,
	"contains":          isContains,
	"doesntContain":     isDoesntContain,
	"requiredArrayKeys": isRequiredArrayKeys,
	"dateFormat":        isDateFormat,
	"after":             isAfter,
	"afterOrEqual":      isAfterOrEqual,
	"before":            isBefore,
	"beforeOrEqual":     isBeforeOrEqual,
	"in":                isIn,
	"notIn":             isNotIn,
	"regex":             isRegex,
	"notRegex":          isNotRegex,
}

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

View Source
var RuleMap = map[string]ValidateFunc{
	"distinct":   isDistinct,
	"accepted":   func(v reflect.Value) (bool, error) { return isAccepted(v), nil },
	"declined":   func(v reflect.Value) (bool, error) { return isDeclined(v), nil },
	"prohibited": func(v reflect.Value) (bool, error) { return isProhibited(v), nil },
	"missing":    func(v reflect.Value) (bool, error) { return isMissing(v), nil },
	"present":    func(v reflect.Value) (bool, error) { return isPresent(v), nil },
	"list":       isList,
	"date":       isDate,
	"json":       isJSON,
	"boolean":    isBoolean,
	"string":     isString,
	"array":      isArray,
	"filled":     isFilled,
}

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

View Source
var StringParamRulesMap = map[string]StringParamValidateFunc{
	"startsWith":      IsStartsWith,
	"endsWith":        IsEndsWith,
	"doesntStartWith": IsDoesntStartWith,
	"doesntEndWith":   IsDoesntEndWith,
}

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

View Source
var StringRulesMap = map[string]StringValidateFunc{
	"numeric":          IsNumeric,
	"int":              IsInt,
	"integer":          IsInt,
	"float":            IsFloat,
	"email":            IsEmail,
	"alpha":            IsAlpha,
	"alphaNum":         IsAlphaNum,
	"alphaDash":        IsAlphaDash,
	"alphaUnicode":     IsAlphaUnicode,
	"alphaNumUnicode":  IsAlphaNumUnicode,
	"alphaDashUnicode": IsAlphaDashUnicode,
	"ip":               IsIP,
	"ipv4":             IsIPv4,
	"ipv6":             IsIPv6,
	"uuid3":            IsUUID3,
	"uuid4":            IsUUID4,
	"uuid5":            IsUUID5,
	"uuid":             IsUUID,
	"ulid":             IsULID,
	"url":              IsURL,
	"hexColor":         IsHexColor,
	"timezone":         IsTimezone,
	"ascii":            IsASCII,
	"lowercase":        IsLowercase,
	"uppercase":        IsUppercase,
	"macAddress":       IsMACAddress,

	"country":         IsCountryCode,
	"country.alpha2":  IsCountryAlpha2,
	"country.alpha3":  IsCountryAlpha3,
	"country.numeric": IsCountryNumeric,

	"currency":        IsCurrencyAll,
	"currency.all":    IsCurrencyAll,
	"currency.fiat":   IsCurrencyFiat,
	"currency.crypto": IsCurrencyCrypto,

	"language":        IsLanguageCode,
	"language.alpha2": IsLanguageAlpha2,
	"language.alpha3": IsLanguageAlpha3,

	"phone.e164": IsPhoneE164,
	"phone":      IsPhoneValid,
}

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

View Source
var (
	ValidateDigitsBetweenInt64 = IsInt64Between
)

Deprecated: Use Is* functions instead.

View Source
var (
	ValidateDigitsBetweenUint64 = IsUint64Between
)

Deprecated: Use Is* functions instead.

Functions

func Empty

func Empty(v reflect.Value) bool

Empty determine whether a variable is empty

func FormatPhoneE164

func FormatPhoneE164(str string, region string) (string, error)

FormatPhoneE164 formats phone number to E.164 format

func FormatPhoneInternational

func FormatPhoneInternational(str string, region string) (string, error)

FormatPhoneInternational formats phone number to international format

func FormatPhoneNational

func FormatPhoneNational(str string, region string) (string, error)

FormatPhoneNational formats phone number to national format

func InString

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

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

func IsASCII

func IsASCII(str string) bool

IsASCII check if the string contains only ASCII characters. Empty string is valid.

func IsAccepted

func IsAccepted(i interface{}) bool

IsAccepted checks if the field is accepted

func IsAfter

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

IsAfter checks if the date is after the given date

func IsAfterOrEqual

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

IsAfterOrEqual checks if the date is after or equal to the given date

func IsAlpha

func IsAlpha(str string) bool

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

func IsAlphaDash

func IsAlphaDash(str string) bool

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

func IsAlphaDashUnicode

func IsAlphaDashUnicode(str string) bool

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

func IsAlphaNum

func IsAlphaNum(str string) bool

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

func IsAlphaNumUnicode

func IsAlphaNumUnicode(str string) bool

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

func IsAlphaUnicode

func IsAlphaUnicode(str string) bool

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

func IsArray

func IsArray(i interface{}) (bool, error)

IsArray checks if the value is an array or slice

func IsBefore

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

IsBefore checks if the date is before the given date

func IsBeforeOrEqual

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

IsBeforeOrEqual checks if the date is before or equal to the given date

func IsBetween

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

IsBetween 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 IsBoolean

func IsBoolean(i interface{}) (bool, error)

IsBoolean checks if the value is boolean-like

func IsContains

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

IsContains is the validation function for validating an array/slice contains specified values.

func IsCountryAlpha2

func IsCountryAlpha2(str string) bool

IsCountryAlpha2 validates ISO 3166-1 alpha-2 country code (2-letter)

func IsCountryAlpha3

func IsCountryAlpha3(str string) bool

IsCountryAlpha3 validates ISO 3166-1 alpha-3 country code (3-letter)

func IsCountryCode

func IsCountryCode(str string) bool

IsCountryCode validates any ISO 3166-1 country code format

func IsCountryNumeric

func IsCountryNumeric(str string) bool

IsCountryNumeric validates ISO 3166-1 numeric country code

func IsCurrencyAll

func IsCurrencyAll(str string) bool

IsCurrencyAll validates any currency (fiat + crypto)

func IsCurrencyCrypto

func IsCurrencyCrypto(str string) bool

IsCurrencyCrypto validates cryptocurrency code

func IsCurrencyFiat

func IsCurrencyFiat(str string) bool

IsCurrencyFiat validates ISO 4217 fiat currency code (3-letter)

func IsDate

func IsDate(i interface{}) (bool, error)

IsDate checks if the value is a valid date

func IsDateAfter

func IsDateAfter(value, after time.Time) bool

IsDateAfter checks if the date is after the given time

func IsDateAfterOrEqual

func IsDateAfterOrEqual(value, after time.Time) bool

IsDateAfterOrEqual checks if the date is after or equal to the given time

func IsDateBefore

func IsDateBefore(value, before time.Time) bool

IsDateBefore checks if the date is before the given time

func IsDateBeforeOrEqual

func IsDateBeforeOrEqual(value, before time.Time) bool

IsDateBeforeOrEqual checks if the date is before or equal to the given time

func IsDateBetween

func IsDateBetween(value, start, end time.Time) bool

IsDateBetween checks if the date is between start and end (exclusive)

func IsDateBetweenOrEqual

func IsDateBetweenOrEqual(value, start, end time.Time) bool

IsDateBetweenOrEqual checks if the date is between start and end (inclusive)

func IsDateFormat

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

IsDateFormat checks if the value matches the given date format

func IsDecimalBetween

func IsDecimalBetween(value, min, max decimal.Decimal) bool

IsDecimalBetween checks if min <= value <= max.

func IsDecimalEqual

func IsDecimalEqual(a, b decimal.Decimal) bool

IsDecimalEqual checks if two decimals are equal.

func IsDecimalGt

func IsDecimalGt(a, b decimal.Decimal) bool

IsDecimalGt checks if a > b.

func IsDecimalGte

func IsDecimalGte(a, b decimal.Decimal) bool

IsDecimalGte checks if a >= b.

func IsDecimalLt

func IsDecimalLt(a, b decimal.Decimal) bool

IsDecimalLt checks if a < b.

func IsDecimalLte

func IsDecimalLte(a, b decimal.Decimal) bool

IsDecimalLte checks if a <= b.

func IsDecimalNegative

func IsDecimalNegative(value decimal.Decimal) bool

IsDecimalNegative checks if value < 0.

func IsDecimalPositive

func IsDecimalPositive(value decimal.Decimal) bool

IsDecimalPositive checks if value > 0.

func IsDecimalPrecision

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

IsDecimalPrecision is the validation function for validating decimal places.

func IsDecimalZero

func IsDecimalZero(value decimal.Decimal) bool

IsDecimalZero checks if decimal is zero.

func IsDeclined

func IsDeclined(i interface{}) bool

IsDeclined checks if the field is declined

func IsDifferent

func IsDifferent(a, b interface{}) (bool, error)

IsDifferent checks if the value is different from another value

func IsDigitsBetween

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

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

func IsDistinct

func IsDistinct(i interface{}) bool

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

func IsDoesntContain

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

IsDoesntContain is the validation function for validating an array/slice does not contain specified values.

func IsDoesntEndWith

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

IsDoesntEndWith check if the string does not end with any of the given suffixes. Empty string is valid.

func IsDoesntStartWith

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

IsDoesntStartWith check if the string does not start with any of the given prefixes. Empty string is valid.

func IsEmail

func IsEmail(str string) bool

IsEmail check if the string is an email.

func IsEmptyString

func IsEmptyString(str string) bool

IsEmptyString check if the string is empty.

func IsEndsWith

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

IsEndsWith check if the string ends with any of the given suffixes. Empty string is valid.

func IsFilled

func IsFilled(i interface{}) (bool, error)

IsFilled checks if the field is not empty when present

func IsFloat

func IsFloat(str string) bool

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

func IsFloat64Between

func IsFloat64Between(value, min, max float64) bool

IsFloat64Between returns true if value lies between min and max (inclusive)

func IsFloat64Gt

func IsFloat64Gt(value, threshold float64) bool

IsFloat64Gt returns true if value is greater than threshold

func IsFloat64Gte

func IsFloat64Gte(value, threshold float64) bool

IsFloat64Gte returns true if value is greater than or equal to threshold

func IsFloat64Lt

func IsFloat64Lt(value, threshold float64) bool

IsFloat64Lt returns true if value is less than threshold

func IsFloat64Lte

func IsFloat64Lte(value, threshold float64) bool

IsFloat64Lte returns true if value is less than or equal to threshold

func IsFuture

func IsFuture(value time.Time) bool

IsFuture checks if the date is in the future

func IsGenericBetween

func IsGenericBetween[T NumericType](value, min, max T) bool

IsGenericBetween checks if min <= value <= max.

func IsGenericDistinct

func IsGenericDistinct[T comparable](value []T) bool

IsGenericDistinct checks if all slice elements are unique.

func IsGenericGt

func IsGenericGt[T OrderedType](value, threshold T) bool

IsGenericGt checks if value > threshold.

func IsGenericGte

func IsGenericGte[T OrderedType](value, threshold T) bool

IsGenericGte checks if value >= threshold.

func IsGenericIn

func IsGenericIn[T comparable](value T, allowed []T) bool

IsGenericIn checks if value is in allowed list.

func IsGenericLt

func IsGenericLt[T OrderedType](value, threshold T) bool

IsGenericLt checks if value < threshold.

func IsGenericLte

func IsGenericLte[T OrderedType](value, threshold T) bool

IsGenericLte checks if value <= threshold.

func IsGenericMax

func IsGenericMax[T NumericType](value, max T) bool

IsGenericMax checks if value <= max.

func IsGenericMin

func IsGenericMin[T NumericType](value, min T) bool

IsGenericMin checks if value >= min.

func IsGenericNotIn

func IsGenericNotIn[T comparable](value T, disallowed []T) bool

IsGenericNotIn checks if value is not in disallowed list.

func IsGenericRequired

func IsGenericRequired[T comparable](value T) bool

IsGenericRequired checks if a comparable value is not zero.

func IsGenericRequiredMap

func IsGenericRequiredMap[K comparable, V any](value map[K]V) bool

IsGenericRequiredMap checks if a map is not empty.

func IsGenericRequiredSlice

func IsGenericRequiredSlice[T any](value []T) bool

IsGenericRequiredSlice checks if a slice is not empty.

func IsGt

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

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

func IsGtParam

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

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

func IsGte

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

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

func IsGteParam

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

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

func IsHexColor

func IsHexColor(str string) bool

IsHexColor check if the string is a valid hex color code. Supports 3 and 6 character formats with or without # prefix. Examples: #fff, #FFF, #ffffff, #FFFFFF, fff, ffffff

func IsIP

func IsIP(v string) bool

IsIP check if the string is an ip address.

func IsIPv4

func IsIPv4(v string) bool

IsIPv4 check if the string is an ipv4 address.

func IsIPv6

func IsIPv6(v string) bool

IsIPv6 check if the string is an ipv6 address.

func IsImage

func IsImage(data []byte) bool

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

func IsIn

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

IsIn checks if the value is in the given list

func IsInt

func IsInt(str string) bool

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

func IsInt64Between

func IsInt64Between(value, min, max int64) bool

IsInt64Between returns true if value lies between min and max (inclusive)

func IsInt64Gt

func IsInt64Gt(value, threshold int64) bool

IsInt64Gt returns true if value is greater than threshold

func IsInt64Gte

func IsInt64Gte(value, threshold int64) bool

IsInt64Gte returns true if value is greater than or equal to threshold

func IsInt64Lt

func IsInt64Lt(value, threshold int64) bool

IsInt64Lt returns true if value is less than threshold

func IsInt64Lte

func IsInt64Lte(value, threshold int64) bool

IsInt64Lte returns true if value is less than or equal to threshold

func IsJSON

func IsJSON(i interface{}) (bool, error)

IsJSON checks if the value is a valid JSON string

func IsLanguageAlpha2

func IsLanguageAlpha2(str string) bool

IsLanguageAlpha2 validates ISO 639-1 language code (2-letter)

func IsLanguageAlpha3

func IsLanguageAlpha3(str string) bool

IsLanguageAlpha3 validates ISO 639-2 language code (3-letter)

func IsLanguageCode

func IsLanguageCode(str string) bool

IsLanguageCode validates any ISO 639 language code format

func IsList

func IsList(i interface{}) (bool, error)

IsList checks if the value is a list (slice or array)

func IsLowercase

func IsLowercase(str string) bool

IsLowercase check if the string is all lowercase. Empty string is valid.

func IsLt

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

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

func IsLtParam

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

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

func IsLte

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

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

func IsLteParam

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

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

func IsMACAddress

func IsMACAddress(str string) bool

IsMACAddress check if the string is a valid MAC address. Supports formats: XX:XX:XX:XX:XX:XX, XX-XX-XX-XX-XX-XX, XXXX.XXXX.XXXX Empty string is valid.

func IsMax

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

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

func IsMaxDigits

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

IsMaxDigits is the validation function for validating the maximum number of digits.

func IsMimeTypes

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

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

func IsMimes

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

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

func IsMin

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

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

func IsMinDigits

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

IsMinDigits is the validation function for validating the minimum number of digits.

func IsMissing

func IsMissing(i interface{}) bool

IsMissing checks if the field is missing

func IsMultipleOf

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

IsMultipleOf is the validation function for validating if a value is a multiple of another.

func IsNotIn

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

IsNotIn checks if the value is not in the given list

func IsNotRegex

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

IsNotRegex checks if the value does not match the given regex pattern

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 IsPast

func IsPast(value time.Time) bool

IsPast checks if the date is in the past

func IsPhone

func IsPhone(str string, region string) bool

IsPhone validates phone number for a specific region (ISO 3166-1 alpha-2)

func IsPhoneE164

func IsPhoneE164(str string) bool

IsPhoneE164 validates phone number in E.164 format (+[country code][number])

func IsPhoneMobile

func IsPhoneMobile(str string, region string) bool

IsPhoneMobile validates if phone number is a mobile number

func IsPhoneValid

func IsPhoneValid(str string) bool

IsPhoneValid validates phone number (any format, any region)

func IsPresent

func IsPresent(i interface{}) bool

IsPresent checks if the field is present

func IsProhibited

func IsProhibited(i interface{}) bool

IsProhibited checks if the field is prohibited (must be empty)

func IsRegex

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

IsRegex checks if the value matches the given regex pattern

func IsRequired

func IsRequired(i interface{}) bool

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

func IsRequiredArrayKeys

func IsRequiredArrayKeys(i interface{}, keys []string) (bool, error)

IsRequiredArrayKeys checks if the map has all the specified keys

func IsSame

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

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

func IsSize

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

IsSize 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 IsStartsWith

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

IsStartsWith check if the string starts with any of the given prefixes. Empty string is valid.

func IsString

func IsString(i interface{}) (bool, error)

IsString checks if the value is a string

func IsStringBetween

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

IsStringBetween checks if string length is between left and right

func IsTimezone

func IsTimezone(str string) bool

IsTimezone check if the string is a valid timezone identifier. Uses Go's time.LoadLocation to validate. Examples: UTC, America/New_York, Europe/London, Asia/Tokyo

func IsToday

func IsToday(value time.Time) bool

IsToday checks if the date is today

func IsULID

func IsULID(str string) bool

IsULID check if the string is a valid ULID. ULID format: 01ARZ3NDEKTSV4RRFFQ69G5FAV (26 characters, Crockford's base32) Empty string is valid.

func IsURL

func IsURL(str string) bool

IsURL check if the string is an URL.

func IsUUID

func IsUUID(str string) bool

IsUUID check if the string is an uuid.

func IsUUID3

func IsUUID3(str string) bool

IsUUID3 check if the string is an uuid3.

func IsUUID4

func IsUUID4(str string) bool

IsUUID4 check if the string is an uuid4.

func IsUUID5

func IsUUID5(str string) bool

IsUUID5 check if the string is an uuid5.

func IsUint64Between

func IsUint64Between(value, min, max uint64) bool

IsUint64Between returns true if value lies between min and max (inclusive)

func IsUint64Gt

func IsUint64Gt(value, threshold uint64) bool

IsUint64Gt returns true if value is greater than threshold

func IsUint64Gte

func IsUint64Gte(value, threshold uint64) bool

IsUint64Gte returns true if value is greater than or equal to threshold

func IsUint64Lt

func IsUint64Lt(value, threshold uint64) bool

IsUint64Lt returns true if value is less than threshold

func IsUint64Lte

func IsUint64Lte(value, threshold uint64) bool

IsUint64Lte returns true if value is less than or equal to threshold

func IsUppercase

func IsUppercase(str string) bool

IsUppercase check if the string is all uppercase. Empty string is valid.

func Now

func Now() time.Time

Now returns the current time

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 Today

func Today() time.Time

Today returns today's date at midnight (00:00:00) in local timezone

func TodayUTC

func TodayUTC() time.Time

TodayUTC returns today's date at midnight (00:00:00) in UTC

func Tomorrow

func Tomorrow() time.Time

Tomorrow returns tomorrow's date at midnight

func ValidateStruct

func ValidateStruct(s interface{}) error

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

func Yesterday

func Yesterday() time.Time

Yesterday returns yesterday's date at midnight

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 DateRule

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

IsDateRule provides fluent date validation building

func Date

func Date(fieldName ...string) *DateRule

Date creates a new DateRule for fluent validation

func (*DateRule) After

func (r *DateRule) After(t time.Time) *DateRule

After adds an "after" validation

func (*DateRule) AfterOrEqual

func (r *DateRule) AfterOrEqual(t time.Time) *DateRule

AfterOrEqual adds an "after or equal" validation

func (*DateRule) Before

func (r *DateRule) Before(t time.Time) *DateRule

Before adds a "before" validation

func (*DateRule) BeforeOrEqual

func (r *DateRule) BeforeOrEqual(t time.Time) *DateRule

BeforeOrEqual adds a "before or equal" validation

func (*DateRule) Between

func (r *DateRule) Between(start, end time.Time) *DateRule

Between adds a "between" validation (exclusive)

func (*DateRule) BetweenOrEqual

func (r *DateRule) BetweenOrEqual(start, end time.Time) *DateRule

BetweenOrEqual adds a "between" validation (inclusive)

func (*DateRule) Validate

func (r *DateRule) Validate(t time.Time) bool

Validate checks if the given time passes all validations

func (*DateRule) ValidateWithError

func (r *DateRule) ValidateWithError(t time.Time) error

ValidateWithError checks if the given time passes all validations and returns an error if not

type DateValidator

type DateValidator func(t time.Time) bool

IsDateValidator represents a date validation function

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 FloatType

type FloatType interface {
	~float32 | ~float64
}

Type constraints for generics

type IntegerType

type IntegerType interface {
	~int | ~int8 | ~int16 | ~int32 | ~int64 |
		~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr
}

Type constraints for generics

type MessageParameters

type MessageParameters []messageParameter

A MessageParameters represents store message parameter into field struct.

type NumericType

type NumericType interface {
	IntegerType | FloatType
}

Type constraints for generics

type OrderedType

type OrderedType interface {
	IntegerType | FloatType | ~string
}

Type constraints for generics

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 TimeHelper

type TimeHelper struct {
	time.Time
}

TimeHelper wraps time.Time with helper methods

func T

func T(t time.Time) TimeHelper

T wraps a time.Time for fluent operations

func (TimeHelper) AddDays

func (t TimeHelper) AddDays(days int) time.Time

AddDays adds days to the time

func (TimeHelper) AddMonths

func (t TimeHelper) AddMonths(months int) time.Time

AddMonths adds months to the time

func (TimeHelper) AddYears

func (t TimeHelper) AddYears(years int) time.Time

AddYears adds years to the time

func (TimeHelper) SubDays

func (t TimeHelper) SubDays(days int) time.Time

SubDays subtracts days from the time

func (TimeHelper) SubMonths

func (t TimeHelper) SubMonths(months int) time.Time

SubMonths subtracts months from the time

func (TimeHelper) SubYears

func (t TimeHelper) SubYears(years int) time.Time

SubYears subtracts years from the time

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