Skip to content

syssam/go-validator

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

139 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

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

About

[Go] Package of validators and support multi languages

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Contributors 3

  •  
  •  
  •  

Languages