A package of validators and sanitizers for strings, structs and collections.
features:
- Customizable Attributes.
- Customizable error messages.
- Support i18n messages
Make sure that Go is installed on your computer. Type the following command in your terminal:
go get github.com/syssam/go-validator
- omitempty
- nullable
- required
- requiredIf
- requiredUnless
- requiredWith
- requiredWithAll
- requiredWithout
- requiredWithoutAll
- between
- digitsBetween
- size
- max
- min
- same
- gt
- gte
- lt
- lte
- distinct
- 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
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.
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
The field under validation must be present and not empty if the anotherfield field is equal to any value.
The field under validation must be present and not empty unless the anotherfield field is equal to any value.
The field under validation must be present and not empty only if any of the other specified fields are present.
The field under validation must be present and not empty only if all of the other specified fields are present.
The field under validation must be present and not empty only when any of the other specified fields are not present.
The field under validation must be present and not empty only when all of the other specified fields are not present.
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.
The field under validation must have a length between the given min and max.
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.
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.
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.
The given field must match the field under validation.
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.
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.
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.
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.
The field under validation must not have any duplicate values.
The field under validation must be formatted as an e-mail address.
The field under validation may be only contains letters. Empty string is valid.
The field under validation may be only contains letters and numbers. Empty string is valid.
The field under validation may be only contains letters, numbers, dashes and underscores. Empty string is valid.
The field under validation may be only contains letters. Empty string is valid.
The field under validation may be only contains letters and numbers. Empty string is valid.
The field under validation may be only contains letters, numbers, dashes and underscores. Empty string is valid.
The field under validation must be numbers. Empty string is valid.
The field under validation must be int. Empty string is valid.
The field under validation must be float. Empty string is valid.
The field under validation must be an IP address.
The field under validation must be an IPv4 address.
The field under validation must be an IPv6 address.
The field under validation must be an uuid3.
The field under validation must be an uuid4.
The field under validation must be an uuid5.
The field under validation must be an uuid.
The field under validation must be a valid URL.
The field under validation must be a valid date.
The field under validation must match the given format. Example: dateFormat=2006-01-02
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 midnighttomorrow- Tomorrow at midnightyesterday- Yesterday at midnightnow- Current timetoday+7d- 7 days from todaytoday-1m- 1 month agotoday-18y- 18 years ago
The field under validation must be a date after or equal to the given date. Supports relative dates.
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
}
The field under validation must be a date before or equal to the given date. Supports relative dates.
The field under validation must match the given regular expression.
type Form struct {
Code string `valid:"regex=^[A-Z]{3}-[0-9]{4}$"`
}
The field under validation must not match the given regular expression.
The field under validation must be included in the given list of values.
The field under validation must not be included in the given list of values.
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".
The field under validation must be "yes", "on", 1, or true.
The field under validation must be "no", "off", 0, or false.
The field under validation must be a valid ISO 3166-1 country code.
countryorcountry.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"`
}
The field under validation must be a valid currency code.
currencyorcurrency.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
}
The field under validation must be a valid ISO 639 language code.
languageorlanguage.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"`
}
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"`
}
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)
validator.CustomTypeTagMap.Set("customValidator", func CustomValidator(v reflect.Value, o reflect.Value, validTag *validator.ValidTag) bool {
return false
})
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
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)
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
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)
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