Documentation
¶
Overview ¶
A package of string validators.
Index ¶
- Constants
- Variables
- func Bool(v bool) *bool
- func Contains(str, seed string, opts *ContainsOpt) (bool, error)
- func Equals(str, comparison string) (bool, error)
- func Float64(v float64) *float64
- func Int(v int) *int
- func IsAbaRouting(str string) (bool, error)
- func IsAfter(str string, opts *IsAfterOpts) (bool, error)
- func IsAlpha(str string, opts *IsAlphaOpts) (bool, error)
- func IsAlphanumeric(str string, opts *IsAlphanumericOpts) (bool, error)
- func IsArray(str string, opts *IsArrayOpts) (bool, error)
- func IsAscii(str string) (bool, error)
- func IsBTCAddress(str string) (bool, error)
- func IsBase32(str string, opts *IsBase32Opts) (bool, error)
- func IsBase58(str string) (bool, error)
- func IsBase64(str string, opts *IsBase64Opts) (bool, error)
- func IsBefore(str string, opts *IsBeforeOpts) (bool, error)
- func IsBic(str string) (bool, error)
- func IsBoolean(str string, opts *IsBooleanOpts) (bool, error)
- func IsByteLength(str string, opts *IsByteLengthOpts) (bool, error)
- func IsCountryCode(str string) (bool, error)
- func IsCreditCard(str string, opts *IsCreditCardOpts) (bool, error)
- func IsCurrency(str string, opts *IsCurrencyOpts) (bool, error)
- func IsDataURI(str string) (bool, error)
- func IsDate(str string, opts *IsDateOpts) (bool, error)
- func IsDecimal(str string, opts *IsDecimalOpts) (bool, error)
- func IsDivisibleBy(str string, num int) (bool, error)
- func IsEAN(str string) (bool, error)
- func IsEmail(str string, opts *IsEmailOpts) (bool, error)
- func IsEmpty(str string, opts *IsEmptyOpts) (bool, error)
- func IsEthereumAddress(str string) (bool, error)
- func IsFQDN(str string, opts *IsFQDNOpts) (bool, error)
- func IsFloat(str string, opts *IsFloatOpts) (bool, error)
- func IsFreightContainerID(str string) (bool, error)
- func IsFullWidth(str string) (bool, error)
- func IsHSL(str string) (bool, error)
- func IsHalfWidth(str string) (bool, error)
- func IsHash(str, algorithm string) (bool, error)
- func IsHexColor(str string) (bool, error)
- func IsHexadecimal(str string) (bool, error)
- func IsIBAN(str, countryCode string) (bool, error)
- func IsIMEI(str string, opts *IsIMEIOpts) (bool, error)
- func IsIP(str, version string) (bool, error)
- func IsIPRange(str, version string) (bool, error)
- func IsISBN(str, version string) (bool, error)
- func IsISIN(str string) (bool, error)
- func IsISO6346(str string) (bool, error)
- func IsISO6391(str string) (bool, error)
- func IsISO8601(str string, opts *IsISO8601Opts) (bool, error)
- func IsISO31661Alpha2(str string) (bool, error)
- func IsISO31661Alpha3(str string) (bool, error)
- func IsISO31661Numeric(str string) (bool, error)
- func IsISRC(str string, allowHyphens bool) (bool, error)
- func IsISSN(str string, opts *IsISSNOpts) (bool, error)
- func IsIdentityCard(str, locale string) (bool, error)
- func IsIn(str string, values []string) (bool, error)
- func IsInt(str string, opts *IsIntOpts) (bool, error)
- func IsIso4217(str string) (bool, error)
- func IsJSON(str string) (bool, error)
- func IsJWT(str string) (bool, error)
- func IsLatLong(str string, opts *IsLatLongOpts) (bool, error)
- func IsLength(str string, opts *IsLengthOpts) (bool, error)
- func IsLicensePlate(str string, locale string) (bool, error)
- func IsLocale(str string) (bool, error)
- func IsLowerCase(str string) (bool, error)
- func IsLuhnNumber(str string) (bool, error)
- func IsMD5(str string) (bool, error)
- func IsMacAddress(str string, opts *IsMacAddressOpts) (bool, error)
- func IsMagnetURI(str string) (bool, error)
- func IsMailtoURI(str string, opts *IsMailToURIOpts) (bool, error)
- func IsMimeType(str string) (bool, error)
- func IsMobilePhone(str string, locales []string, opts *IsMobilePhoneOpts) (bool, error)
- func IsMongoID(str string) (bool, error)
- func IsMultibyte(str string) (bool, error)
- func IsNumeric(str string, opts *IsNumericOpts) (bool, error)
- func IsObject(str string, opts *IsObjectOpts) (bool, error)
- func IsOctal(str string) (bool, error)
- func IsPassportNumber(str, countryCode string) (bool, error)
- func IsPort(str string) (bool, error)
- func IsPostalCode(str, locale string) (bool, error)
- func IsRFC3339(str string) (bool, error)
- func IsRgbColor(str string, opts *IsRgbOpts) (bool, error)
- func IsSemVer(str string) (bool, error)
- func IsSlug(str string) (bool, error)
- func IsStrongPassword(str string, opts *IsStrongPasswordOpts) (bool, float64, error)
- func IsSurrogatePair(str string) (bool, error)
- func IsTaxID(str, locale string) (bool, error)
- func IsTime(str string, opts *IsTimeOpts) (bool, error)
- func IsULID(str string) (bool, error)
- func IsURL(str string, opts *IsURLOpts) (bool, error)
- func IsUUID(str, version string) (bool, error)
- func IsUpperCase(str string) (bool, error)
- func IsVAT(str, countryCode string) (bool, error)
- func IsVariableWidth(str string) (bool, error)
- func IsWhitelisted(str, chars string) (bool, error)
- func Matches(str string, re *regexp.Regexp) (bool, error)
- func String(v string) *string
- func Uint(v uint) *uint
- type ContainsOpt
- type DecimalDigits
- type IsAfterOpts
- type IsAlphaOpts
- type IsAlphanumericOpts
- type IsArrayOpts
- type IsBase32Opts
- type IsBase64Opts
- type IsBeforeOpts
- type IsBooleanOpts
- type IsByteLengthOpts
- type IsCreditCardOpts
- type IsCurrencyOpts
- type IsDateOpts
- type IsDecimalOpts
- type IsEmailOpts
- type IsEmptyOpts
- type IsFQDNOpts
- type IsFloatOpts
- type IsIMEIOpts
- type IsISO8601Opts
- type IsISSNOpts
- type IsIntOpts
- type IsLatLongOpts
- type IsLengthOpts
- type IsMacAddressOpts
- type IsMailToURIOpts
- type IsMobilePhoneOpts
- type IsNumericOpts
- type IsObjectOpts
- type IsRgbOpts
- type IsStrongPasswordOpts
- type IsTimeOpts
- type IsURLOpts
- type ValidationError
Constants ¶
const ( ErrInvalidFormat = "invalid_format" ErrTooShort = "too_short" ErrTooLong = "too_long" ErrMissingTLD = "missing_tld" ErrBlacklistedHost = "blacklisted_host" ErrNotWhitelistedHost = "not_whitelisted_host" ErrBlacklistedChar = "blacklisted_char" ErrInvalidLocale = "invalid_locale" ErrOutOfRange = "out_of_range" ErrInvalidChecksum = "invalid_checksum" ErrInvalidLength = "invalid_length" ErrMissingRequired = "missing_required" ErrInvalidDomain = "invalid_domain" ErrUnsupportedVersion = "unsupported_version" ErrInvalidValue = "invalid_value" ErrNotFound = "not_found" )
Error code constants for validation failures.
const ( StandardDateLayout = "2006-01-02" SlashDateLayout = "2006/01/02" DateTimeLayout = "2006-01-02 15:04:05" ISO8601Layout = "2006-01-02T15:04:05" ISO8601ZuluLayout = "2006-01-02T15:04:05Z" ISO8601WithMillisecondsLayout = "2006-01-02T15:04:05.000Z" )
IsDate formats
Variables ¶
var ( IsTimeOptsHourFormat24 string = "hour24" IsTimeOptsHourFormat12 string = "hour12" IsTimeOptsModeDefault string = "default" IsTimeOptsModeWithSeconds string = "withSeconds" )
var AllCountryCodes = [...]string{} /* 237 elements not displayed */
var AllISO31661Alpha2 = [...]string{}/* 676 elements not displayed */
var AllISO31661Alpha3 = [...]string{}/* 243 elements not displayed */
var AllISO31661Numeric = [...]string{} /* 251 elements not displayed */
var AllISO4217Codes = [...]string{}/* 184 elements not displayed */
var AllISO6391Codes = [...]string{} /* 176 elements not displayed */
var AllLocales = [...]string{} /* 490 elements not displayed */
var (
IsObjectOptsDefaultStrict = true
)
Functions ¶
func Bool ¶ added in v1.0.0
Bool returns a pointer to the given bool value. Use this when setting pointer fields on option structs.
IsEmail("[email protected]", &IsEmailOpts{AllowUTF8LocalPart: Bool(false)})
func Contains ¶
func Contains(str, seed string, opts *ContainsOpt) (bool, error)
A validator that checks if the string contains the seed.
ContainsOpt is a struct that defaults to { IgnoreCase: false, MinOccurrences: 1 }.
ContainsOpt:
IgnoreCase: Ignore case when doing comparison, default false.
MinOccurrences: Minimum number of occurrences for the seed in the string. Defaults to 1.
ok, _ := validatorgo.Contains("hello world", "world", nil)
fmt.Println(ok) // true
ok, _ = validatorgo.Contains("hello world", "earth", nil)
fmt.Println(ok) // false
func Equals ¶
A validator that checks if the string matches the comparison.
ok, _ := validatorgo.Equals("Hello", "Hello")
fmt.Println(ok) // true
ok, _ = validatorgo.Equals("Hello", "World")
fmt.Println(ok) // false
func IsAbaRouting ¶
A validator that checks if the string is an ABA routing number for US bank account / cheque.
ok, _ := validatorgo.IsAbaRouting("123456789")
fmt.Println(ok) // false
ok, _ = validatorgo.IsAbaRouting("021000021")
fmt.Println(ok) // true
func IsAfter ¶
func IsAfter(str string, opts *IsAfterOpts) (bool, error)
A validator that checks if the string is a date that is after the specified date.
IsAfterOpts is a struct that defaults to { ComparisonDate: "" }.
IsAfterOpts:
ComparisonDate: defaults to the current time.
string layouts for str and ComparisonDate can be different layout.
these are the only valid layouts from the time package e.g Layout, ANSIC, UnixDate, RubyDate, RFC822, RFC822Z, RFC850, RFC1123, RFC1123Z, Kitchen, Stamp, StampMilli, StampMicro, StampNano, DateTime, DateOnly, TimeOnly, StandardDateLayout, SlashDateLayout, DateTimeLayout, ISO8601Layout, ISO8601ZuluLayout, ISO8601WithMillisecondsLayout.
ok, _ := validatorgo.IsAfter("2023-09-15", &validatorgo.IsAfterOpts{ComparisonDate: "2023-01-01"})
fmt.Println(ok) // true
ok, _ = validatorgo.IsAfter("2023-01-01", &validatorgo.IsAfterOpts{ComparisonDate: "2023-09-15"})
fmt.Println(ok) // false
func IsAlpha ¶
func IsAlpha(str string, opts *IsAlphaOpts) (bool, error)
A validator that checks if the string contains only letters (a-zA-Z).
IsAlphaOpts is an optional struct that can be supplied with the following key(s):
Ignore: is the string to be ignored e.g. " -" will ignore spaces and -'s.
Locale: one of ("ar", "ar-AE", "ar-BH", "ar-DZ", "ar-EG", "ar-IQ", "ar-JO", "ar-KW", "ar-LB", "ar-LY", "ar-MA", "ar-QA", "ar-QM", "ar-SA", "ar-SD", "ar-SY", "ar-TN", "ar-YE", "bg-BG", "bn", "cs-CZ", "da-DK", "de-DE", "el-GR", "en-AU", "en-GB", "en-HK", "en-IN", "en-NZ", "en-US", "en-ZA", "en-ZM", "eo", "es-ES", "fa-IR", "fi-FI", "fr-CA", "fr-FR", "he", "hi-IN", "hu-HU", "it-IT", "kk-KZ", "ko-KR", "ja-JP", "ku-IQ", "nb-NO", "nl-NL", "nn-NO", "pl-PL", "pt-BR", "pt-PT", "ru-RU", "si-LK", "sl-SI", "sk-SK", "sr-RS", "sr-RS@latin", "sv-SE", "th-TH", "tr-TR", "uk-UA") and defaults to en-US if none is provided.
ok, _ := validatorgo.IsAlpha("hello", nil)
fmt.Println(ok) // true
ok, _ = validatorgo.IsAlpha("hello123", nil)
fmt.Println(ok) // false
func IsAlphanumeric ¶
func IsAlphanumeric(str string, opts *IsAlphanumericOpts) (bool, error)
A validator that checks if the string contains only letters and numbers (a-zA-Z0-9).
IsAlphaOpts is an optional struct that can be supplied with the following key(s):
Ignore: is the string to be ignored e.g. " -" will ignore spaces and -'s.
locale is one of ("ar", "ar-AE", "ar-BH", "ar-DZ", "ar-EG", "ar-IQ", "ar-JO", "ar-KW", "ar-LB", "ar-LY", "ar-MA", "ar-QA", "ar-QM", "ar-SA", "ar-SD", "ar-SY", "ar-TN", "ar-YE", "bn", "bg-BG", "cs-CZ", "da-DK", "de-DE", "el-GR", "en-AU", "en-GB", "en-HK", "en-IN", "en-NZ", "en-US", "en-ZA", "en-ZM", "eo", "es-ES", "fa-IR", "fi-FI", "fr-CA", "fr-FR", "he", "hi-IN", "hu-HU", "it-IT", "kk-KZ", "ko-KR", "ja-JP","ku-IQ", "nb-NO", "nl-NL", "nn-NO", "pl-PL", "pt-BR", "pt-PT", "ru-RU", "si-LK", "sl-SI", "sk-SK", "sr-RS", "sr-RS@latin", "sv-SE", "th-TH", "tr-TR", "uk-UA") and defaults to en-US.
ok, _ := validatorgo.IsAlphanumeric("hello123", nil)
fmt.Println(ok) // true
ok, _ = validatorgo.IsAlphanumeric("hello!", nil)
fmt.Println(ok) // false
func IsArray ¶
func IsArray(str string, opts *IsArrayOpts) (bool, error)
A validator to check that a value is an array.
IsArrayOpts is a struct which defaults to { Min: nil, Max: nil }.
You can also check that the array's length is greater than or equal to IsArrayOpts.Min and/or that it's less than or equal to IsArrayOpts.Max.
ok, _ := validatorgo.IsArray(`["item1", "item2"]`, nil)
fmt.Println(ok) // true
ok, _ = validatorgo.IsArray(`{"name": "John", "age": 30}`, nil)
fmt.Println(ok) // false
func IsAscii ¶
A validator that checks if the string contains ASCII chars only.
ok, _ := validatorgo.IsAscii("Hello")
fmt.Println(ok) // true
ok, _ = validatorgo.IsAscii("こんにちは")
fmt.Println(ok) // false
func IsBTCAddress ¶
A validator that checks if the string is a valid BTC address.
ok, _ := validatorgo.IsBTCAddress("1RAHUEYstWetqabcFn5Au4m4GFg7xJaNVN2")
fmt.Println(ok) // true
ok, _ = validatorgo.IsBTCAddress("0J98t1RHT73CNmQwertyyWrnqRhWNLy")
fmt.Println(ok) // false
func IsBase32 ¶
func IsBase32(str string, opts *IsBase32Opts) (bool, error)
A validator that checks if the string is base32 encoded.
IsBase32Opts defaults to { Crockford: false }. When Crockford is true it tests the given base32 encoded string using crockford's base32 alternative.
ok, _ := validatorgo.IsBase32("JBSWY3DPEBLW64TMMQ", nil)
fmt.Println(ok) // true
ok, _ = validatorgo.IsBase32("jbswy3dpeblw64tmmq======", nil)
fmt.Println(ok) // false
func IsBase64 ¶
func IsBase64(str string, opts *IsBase64Opts) (bool, error)
A validator that checks if the string is base64 encoded.
IsBase64Opts is an optional struct which defaults to { UrlSafe: false }. When UrlSafe is true it tests the given base64 encoded string is url safe.
ok, _ := validatorgo.IsBase64("SGVsbG8gd29ybGQ", nil)
fmt.Println(ok) // true
ok, _ = validatorgo.IsBase64("SGVsbG8g@d29ybGQ=", nil)
fmt.Println(ok) // false
func IsBefore ¶
func IsBefore(str string, opts *IsBeforeOpts) (bool, error)
A validator that checks if the string is a date that is before the specified date.
IsBeforeOpts is a struct that defaults to { ComparisonDate: "" }.
IsBeforeOpts:
ComparisonDate: defaults to the current time. string layouts for str and ComparisonDate can be different layout. these are the only valid layouts from the time package e.g Layout, ANSIC, UnixDate, RubyDate, RFC822, RFC822Z, RFC850, RFC1123, RFC1123Z, Kitchen, Stamp, StampMilli, StampMicro, StampNano, DateTime, DateOnly, TimeOnly, StandardDateLayout, SlashDateLayout, DateTimeLayout, ISO8601Layout, ISO8601ZuluLayout, ISO8601WithMillisecondsLayout.
ok, _ := validatorgo.IsBefore("2023-01-01", &validatorgo.IsBeforeOpts{ComparisonDate: "2023-09-15"})
fmt.Println(ok) // true
ok, _ = validatorgo.IsBefore("2024-01-01", &validatorgo.IsBeforeOpts{ComparisonDate: "2023-01-01"})
fmt.Println(ok) // false
func IsBic ¶
A validator that checks if the string is a BIC (Bank Identification Code) or SWIFT code.
ok, _ := validatorgo.IsBic("DEUTDEFF")
fmt.Println(ok) // true
ok, _ = validatorgo.IsBic("ABCDUS12XXXX")
fmt.Println(ok) // false
func IsBoolean ¶
func IsBoolean(str string, opts *IsBooleanOpts) (bool, error)
A validator that check if the string is a boolean.
IsBooleanOpts is a struct which defaults to { Loose: false } and that can be supplied with the following key(s):
Loose: If Loose is set to false, the validator will strictly match ['true', 'false', '0', '1']. If Loose is set to true, the validator will also match 'yes', 'no', and will match a valid boolean string of any case. (e.g.: ['true', 'True', 'TRUE', "false", "False", "FALSE"]).
ok, _ := validatorgo.IsBoolean("true", &validatorgo.IsBooleanOpts{Loose: false})
fmt.Println(ok) // true
ok, _ = validatorgo.IsBoolean("bool", &validatorgo.IsBooleanOpts{Loose: false})
fmt.Println(ok) // false
func IsByteLength ¶
func IsByteLength(str string, opts *IsByteLengthOpts) (bool, error)
A validator that checks if the string's length (in UTF-8 bytes) falls in a range.
IsByteLengthOpts is a struct which defaults to { Min: 0, Max: nil }.
ok, _ := validatorgo.IsByteLength("We♥Go", &validatorgo.IsByteLengthOpts{Min: 5})
fmt.Println(ok) // true
ok, _ = validatorgo.IsByteLength("We♥Go", &validatorgo.IsByteLengthOpts{Min: 8})
fmt.Println(ok) // false
func IsCountryCode ¶
A validator that checks if the string is a country code.
func IsCreditCard ¶
func IsCreditCard(str string, opts *IsCreditCardOpts) (bool, error)
A validator that checks if the string is a credit card number.
IsCreditCardOpts is an struct that can be supplied with the following key(s):
Provider: is a key whose value should be a string, and defines the company issuing the credit card. Valid values include amex, bcglobal, carteblanche, dinersclub, discover, instapayment, jcb, koreanlocal, laser, maestro, mastercard, solo, switch, unionpay, visa, visamastercard or blank will check for any provider.
ok, _ := validatorgo.IsCreditCard("378282246310005", &validatorgo.IsCreditCardOpts{Provider: "amex"})
fmt.Println(ok) // true
ok, _ = validatorgo.IsCreditCard("37828224631000", &validatorgo.IsCreditCardOpts{Provider: "amex"})
fmt.Println(ok) // false
func IsCurrency ¶
func IsCurrency(str string, opts *IsCurrencyOpts) (bool, error)
A validator that checks if the string is a valid currency amount.
IsCurrencyOpts is a struct which defaults to { Symbol: '$', RequireSymbol: false, AllowSpaceAfterSymbol: false, SymbolAfterDigits: false, AllowNegatives: true, ParensForNegatives: false, NegativeSignBeforeDigits: false, NegativeSignAfterDigits: false, AllowNegativeSignPlaceholder: false, ThousandsSeparator: ',', DecimalSeparator: '.', AllowDecimal: true, RequireDecimal: false, MaxDigitsAfterDecimal: 2, AllowSpaceAfterDigits: false }.
ok, _ := validatorgo.IsCurrency("$100,000.00", nil)
fmt.Println(ok) // true
ok, _ = validatorgo.IsCurrency("¥100", &validatorgo.IsCurrencyOpts{Symbol: String("¥"), RequireSymbol: Bool(true)})
fmt.Println(ok) // true
ok, _ = validatorgo.IsCurrency("100.50", &validatorgo.IsCurrencyOpts{Symbol: String("$"), RequireSymbol: Bool(true)})
fmt.Println(ok) // false
func IsDataURI ¶
A validator that checks if the string is a data uri format.
ok, _ := validatorgo.IsDataURI("data:,Hello%2C%20World%21")
fmt.Println(ok) // true
ok, _ = validatorgo.IsDataURI("text/plain;base64,SGVsbG8sIFdvcmxkIQ==")
fmt.Println(ok) // false
func IsDate ¶
func IsDate(str string, opts *IsDateOpts) (bool, error)
A Validator that checks if the string is a valid date. e.g. 2002-07-15.
IsDateOpts is a struct which can contain the keys Format, StrictMode.
Format: is a string and defaults to validatorgo.StandardDateLayout if "any" or no value is provided.
StrictMode: is a boolean and defaults to false. If StrictMode is set to true, the validator will reject strings different from Format.
ok, _ := validatorgo.IsDate("2006-01-02", nil)
fmt.Println(ok) // true
ok, _ = validatorgo.IsDate("01/023/2006", nil)
fmt.Println(ok) // false
func IsDecimal ¶
func IsDecimal(str string, opts *IsDecimalOpts) (bool, error)
A validator that check if the string represents a decimal number, such as 0.1, .3, 1.1, 1.00003, 4.0, etc.
IsDecimalOpts is a struct which defaults to {ForceDecimal: false, DecimalDigits: {Min: 0, Max: nil}, locale: 'en-US'}.
locale: determines the decimal separator and is one of ("ar", "ar-AE", "ar-BH", "ar-DZ", "ar-EG", "ar-IQ", "ar-JO", "ar-KW", "ar-LB", "ar-LY", "ar-MA", "ar-QA", "ar-QM", "ar-SA", "ar-SD", "ar-SY", "ar-TN", "ar-YE", "bg-BG", "cs-CZ", "da-DK", "de-DE", "el-GR", "en-AU", "en-GB", "en-HK", "en-IN", "en-NZ", "en-US", "en-ZA", "en-ZM", "eo", "es-ES", "fa", "fa-AF", "fa-IR", "fr-FR", "fr-CA", "hu-HU", "id-ID", "it-IT", "ku-IQ", "nb-NO", "nl-NL", "nn-NO", "pl-PL", "pl-Pl", "pt-BR", "pt-PT", "ru-RU", "sl-SI", "sr-RS", "sr-RS@latin", "sv-SE", "tr-TR", "uk-UA", "vi-VN"). Locale defaults to "en-US"
ForceDecimal: simply means a decimal must be present "123" will not pass but "123.45" will pass
DecimalDigits: is the allowed decimal range e.g {Min: 3, Max: nil} 123.456
ok, _ := validatorgo.IsDecimal("123", nil)
fmt.Println(ok) // true
ok, _ = validatorgo.IsDecimal("abc", nil)
fmt.Println(ok) // false
func IsDivisibleBy ¶
A validator thats checks if the string is a number(integer not a floating point) that is divisible by another(integer not a floating point).
ok, _ := validatorgo.IsDivisibleBy("10", 2)
fmt.Println(ok) // true
ok, _ = validatorgo.IsDivisibleBy("10", 3)
fmt.Println(ok) // false
func IsEAN ¶
IsEAN checks if the string is a valid EAN (European Article Number).
ok, _ := validatorgo.IsDecimal("4006381333931")
fmt.Println(ok) // true
ok, _ = validatorgo.IsDecimal("123456789012")
fmt.Println(ok) // false
func IsEmail ¶
func IsEmail(str string, opts *IsEmailOpts) (bool, error)
A validator that checks if the string is an email.
IsEmailOpts is a struct which defaults to { AllowDisplayName: false, RequireDisplayName: false, AllowUTF8LocalPart: true, RequireTld: true, AllowIpDomain: false, isEmailDefaultIgnoreMaxLength: false, DomainSpecificValidation: false, BlacklistedChars: "", HostBlacklist: [] }.
AllowDisplayName: if set to true, the validator will also match Display Name <email-address>. RequireDisplayName: if set to true, the validator will reject strings without the format Display Name <email-address>. AllowUTF8LocalPart: if set to false, the validator will not allow any non-English UTF8 character in email address' local part. RequireTld: if set to false, email addresses without a TLD in their domain will also be matched. IgnoreMaxLength: if set to true, the validator will not check for the standard max length of an email. AllowIpDomain: if set to true, the validator will allow IP addresses in the host part. DomainSpecificValidation: is true, some additional validation will be enabled, e.g. disallowing certain syntactically valid email addresses that are rejected by Gmail. BlacklistedChars: receives a string, then the validator will reject emails that include any of the characters in the string, in the name part. HostBlacklist: if set to an slice of strings and the part of the email after the @ symbol matches one of the strings defined in it, the validation fails. HostWhitelist: if set to an slice of strings and the part of the email after the @ symbol matches none of the strings defined in it, the validation fails.
ok, _ := validatorgo.IsEmail("[email protected]", nil)
fmt.Println(ok) // true
ok, _ = validatorgo.IsEmail("user.example.com", nil)
fmt.Println(ok) // false
func IsEmpty ¶
func IsEmpty(str string, opts *IsEmptyOpts) (bool, error)
A validator check if the string has a length of zero.
IsEmptyOpts is a struct which defaults to { IgnoreWhitespace: false }.
ok, _ := validatorgo.IsEmpty("", nil)
fmt.Println(ok) // true
ok, _ = validatorgo.IsEmpty("abc", nil)
fmt.Println(ok) // false
func IsEthereumAddress ¶
A validator checks if the string is an Ethereum address. Does not validate address checksums.
ok, _ := validatorgo.IsEthereumAddress("0xeA0B9657892321121287128712BC78A89F989AAA")
fmt.Println(ok) // true
ok, _ = validatorgo.IsEthereumAddress("0xiuahbsndakjsd")
fmt.Println(ok) // false
func IsFQDN ¶
func IsFQDN(str string, opts *IsFQDNOpts) (bool, error)
A validator that checks if the string is a fully qualified domain name (e.g. domain.com).
IsFQDNOpts is a struct which defaults to { RequireTld: true, AllowUnderscores: false, AllowTrailingDot: false, AllowNumericTld: false, allow_wildcard: false, IgnoreMaxLength: false }.
ok, _ := validatorgo.IsFQDN("localhost", nil)
fmt.Println(ok) // true
ok, _ = validatorgo.IsFQDN("example..com", nil)
fmt.Println(ok) // false
func IsFloat ¶
func IsFloat(str string, opts *IsFloatOpts) (bool, error)
A validator that checks if the string is a float.
IsFloatOpts is a struct which can contain the fields Min, Max, Gt, and/or Lt to validate the float is within boundaries it also has Locale as an option.
Min and Max: are equivalent to 'greater or equal' and 'less or equal'.
Gt and Lt: are their strict counterparts.
Locale determines the decimal separator and is one of ("ar", "ar-AE", "ar-BH", "ar-DZ", "ar-EG", "ar-IQ", "ar-JO", "ar-KW", "ar-LB", "ar-LY", "ar-MA", "ar-QA", "ar-QM", "ar-SA", "ar-SD", "ar-SY", "ar-TN", "ar-YE", "bg-BG", "cs-CZ", "da-DK", "de-DE", "en-AU", "en-GB", "en-HK", "en-IN", "en-NZ", "en-US", "en-ZA", "en-ZM", "eo", "es-ES", "fr-CA", "fr-FR", "hu-HU", "it-IT", "nb-NO", "nl-NL", "nn-NO", "pl-PL", "pt-BR", "pt-PT", "ru-RU", "sl-SI", "sr-RS", "sr-RS@latin", "sv-SE", "tr-TR", "uk-UA").
ok, _ := validatorgo.IsFloat("123.45", nil)
fmt.Println(ok) // true
ok, _ = validatorgo.IsFloat("123", nil)
fmt.Println(ok) // false
func IsFreightContainerID ¶
A validator that checks alias for IsISO6346, check if the string is a valid ISO 6346 shipping container identification.
ok, _ := validatorgo.IsFreightContainerID("ABCU1234567")
fmt.Println(ok) // true
ok, _ = validatorgo.IsFreightContainerID("AB123456789")
fmt.Println(ok) // false
func IsFullWidth ¶
A validator that checks if the string contains any full-width chars.
ok, _ := validatorgo.IsFullWidth("テスト")
fmt.Println(ok) // true
ok, _ = validatorgo.IsFullWidth("abc123")
fmt.Println(ok) // false
func IsHSL ¶
A validator that checks if the string is an HSL (hue, saturation, lightness, optional alpha) color based on CSS Colors Level 4 specification.
ok, _ := validatorgo.IsHSL("hsl(360, 100%, 50%)")
fmt.Println(ok) // true
ok, _ = validatorgo.IsHSL("hsl(360, 100%)")
fmt.Println(ok) // false
func IsHalfWidth ¶
A validator that checks if the string contains any half-width chars.
ok, _ := validatorgo.IsHalfWidth("abc123")
fmt.Println(ok) // true
ok, _ = validatorgo.IsHalfWidth("漢字テスト")
fmt.Println(ok) // false
func IsHash ¶
A validator that checks if the string is a hash of type algorithm.
Algorithm is one of ("crc32", "crc32b", "md4", "md5", "ripemd128", "ripemd160", "sha1", "sha256", "sha384", "sha512", "tiger128", "tiger160", "tiger192"), No checksum are calculated.
ok, _ := validatorgo.IsHash("d202ef8d", "crc32")
fmt.Println(ok) // true
ok, _ = validatorgo.IsHash("d202ef8", "crc32")
fmt.Println(ok) // false
func IsHexColor ¶
A validator that checks if the string is a hexadecimal color.
ok, _ := validatorgo.IsHexColor("#abc")
fmt.Println(ok) // true
ok, _ = validatorgo.IsHexColor("#xyz")
fmt.Println(ok) // false
func IsHexadecimal ¶
A validator that checks if the string is a hexadecimal number.
ok, _ := validatorgo.IsHexadecimal("1234567890abcdef")
fmt.Println(ok) // true
ok, _ = validatorgo.IsHexadecimal("abcdefg")
fmt.Println(ok) // false
func IsIBAN ¶
A validator that checks if the string is an IBAN (International Bank Account Number).
these are the allowed country codes ("AD","AE","AL","AT","AZ","BA","BE","BG","BH","BR","BY","CH","CR","CY","CZ","DE","DK","DO","EE","EG","ES","FI","FO","FR","GB","GE","GI","GL","GR","GT","HR","HU","IE","IL","IQ","IR","IS","IT","JO","KW","KZ","LB","LC","LI","LT","LU","LV","MC","MD","ME","MK","MR","MT","MU","MZ","NL","NO","PK","PL","PS","PT","QA","RO","RS","SA","SC","SE","SI","SK","SM","SV","TL","TN","TR","UA","VA","VG","XK"). No checksum are calculated.
ok, _ := validatorgo.IsIBAN("DE75512108001245126199", "DE")
fmt.Println(ok) // true
ok, _ = validatorgo.IsIBAN("DE75512108001245126100", "DE")
fmt.Println(ok) // false
func IsIMEI ¶
func IsIMEI(str string, opts *IsIMEIOpts) (bool, error)
A validator that checks if the string is a valid IMEI number. IMEI should be of format ############### or ##-######-######-#.
IsIMEIOpts is a struct which can contain the keys AllowHyphens. Defaults to first format.
If AllowHyphens is set to true, the validator will validate the second format.
ok, _ := validatorgo.IsIMEI("490154203237518", nil)
fmt.Println(ok) // true
ok, _ = validatorgo.IsIMEI("359043377500085", nil)
fmt.Println(ok) // false
func IsIP ¶
A validator that checks if the string is an IP (version 4 or 6). If version is not provide, both versions "4" and "6" will be checked.
ok, _ := validatorgo.IsIP("192.168.0.1", "4")
fmt.Println(ok) // true
ok, _ = validatorgo.IsIP("256.256.256.256", "4")
fmt.Println(ok) // false
func IsIPRange ¶
A validator that checks if the string is an IP Range (version 4 or 6). If version is not provide, both versions "4" and "6" will be checked.
ok, _ := validatorgo.IsIPRange("192.168.0.0/24", "4")
fmt.Println(ok) // true
ok, _ = validatorgo.IsIPRange("192.168.0.0/33", "4")
fmt.Println(ok) // false
func IsISBN ¶
A validator that checks if the string is an ISBN.
version: ISBN version to compare to. Accepted values are "10" and "13". If none provided, both will be tested.
ok, _ := validatorgo.IsISBN("0-7167-0344-0", "10")
fmt.Println(ok) // true
ok, _ = validatorgo.IsISBN("0-7168-0344-0", "10")
fmt.Println(ok) // false
func IsISIN ¶
A validator that checks if the string is an ISIN (stock/security identifier).
ok, _ := validatorgo.IsISIN("US0378331005")
fmt.Println(ok) // true
ok, _ = validatorgo.IsISIN("US0373831005")
fmt.Println(ok) // false
func IsISO6346 ¶
A validator that checks if the string is a valid ISO 6346 shipping container identification.
ok, _ := validatorgo.IsISO6346("CSQU3054383")
fmt.Println(ok) // true
ok, _ = validatorgo.IsISO6346("CSQX3054383")
fmt.Println(ok) // false
func IsISO6391 ¶
A validator that checks if the string is a valid ISO 639-1 language code.
ok, _ := validatorgo.IsISO6391("en")
fmt.Println(ok) // true
ok, _ = validatorgo.IsISO6391("eng")
fmt.Println(ok) // false
func IsISO8601 ¶
func IsISO8601(str string, opts *IsISO8601Opts) (bool, error)
A validator that checks if the string is a valid ISO 8601 date.
IsISO8601Opts is a struct which defaults to { Strict: false, StrictSeparator: false }.
If Strict is true, date strings with invalid dates like 2009-02-29 will be invalid.
If StrictSeparator is true, date strings with date and time separated by anything other than a T will be invalid.
ok, _ := validatorgo.IsISO8601("2023-09-05", nil)
fmt.Println(ok) // true
ok, _ = validatorgo.IsISO8601("2023-13-05T14:30:00", nil)
fmt.Println(ok) // false
func IsISO31661Alpha2 ¶
A validator that checks if the string is a valid ISO 3166-1 alpha-2 officially assigned country code.
ok, _ := validatorgo.IsISO31661Alpha2("EN")
fmt.Println(ok) // true
ok, _ = validatorgo.IsISO31661Alpha2("eng")
fmt.Println(ok) // false
func IsISO31661Alpha3 ¶
A validator that checks if the string is a valid ISO 3166-1 alpha-3 officially assigned country code.
ok, _ := validatorgo.IsISO31661Alpha3("ABW")
fmt.Println(ok) // true
ok, _ = validatorgo.IsISO31661Alpha3("ES")
fmt.Println(ok) // false
func IsISO31661Numeric ¶
A validator that checks check if the string is a valid ISO 3166-1 numeric officially assigned country code.
ok, _ := validatorgo.IsISO31661Numeric("032")
fmt.Println(ok) // true
ok, _ = validatorgo.IsISO31661Numeric("56")
fmt.Println(ok) // false
func IsISRC ¶
A validator that checks if the string is an ISRC.
allowHyphens will allow codes with dashes present CC-XXX-YY-NNNNN
ok, _ := validatorgo.IsISRC("AASKG1912345", false)
fmt.Println(ok) // true
ok, _ = validatorgo.IsISRC("AA-SKG-19-12345", false)
fmt.Println(ok) // false
func IsISSN ¶
func IsISSN(str string, opts *IsISSNOpts) (bool, error)
A validator that checks if the string is an ISSN.
IsISSNOpts is a struct which defaults to { CaseSensitive: false, RequireHyphen: false }.
If CaseSensitive is true, ISSNs with a lowercase "x" as the check digit are rejected.
ok, _ := validatorgo.IsISSN("0378-5955", nil)
fmt.Println(ok) // true
ok, _ = validatorgo.IsISSN("1234567", nil)
fmt.Println(ok) // false
func IsIdentityCard ¶
A validator that checks if the string is a valid identity card code.
locale is one of ("LK", "PL", "ES", "FI", "IN", "IT", "IR", "MZ", "NO", "TH", "zh-TW", "he-IL", "ar-LY", "ar-TN", "zh-CN", "zh-HK", "PK") OR "any". If "any" is used, function will check if any of the locales match. Defaults to "any" if locale not present. No checksums calculated.
ok, _ := validatorgo.IsIdentityCard("123456789V", "LK")
fmt.Println(ok) // true
ok, _ = validatorgo.IsIdentityCard("12345678X", "LK")
fmt.Println(ok) // false
func IsIn ¶
A validator that checks if the string is in a slice of allowed values.
ok, _ := validatorgo.IsIn("apple", []string{"apple", "banana", "grape"})
fmt.Println(ok) // true
ok, _ = validatorgo.IsIn("orange", []string{"apple", "banana", "grape"})
fmt.Println(ok) // false
func IsInt ¶
A validator that checks if the string is an integer.
IsIntOpts is a struct which can contain the keys Min and/or Max to check the integer is within boundaries (e.g. { Min: nil, Max: nil }).
IsIntOpts can also contain the key AllowLeadingZeroes, which when set to false will disallow integer values with leading zeroes (e.g. { AllowLeadingZeroes: false }).
Finally, IsIntOpts can contain the keys Gt and/or Lt which will enforce integers being greater than or less than, respectively, the value provided (e.g. {Gt: ptr(1), Lt: ptr(4)} for a number between 1 and 4).
ok, _ := validatorgo.IsInt("123", nil)
fmt.Println(ok) // true
ok, _ = validatorgo.IsInt("123.45", nil)
fmt.Println(ok) // false
func IsIso4217 ¶
A validator that checks if the string is a valid ISO 4217 officially assigned currency code.
ok, _ := validatorgo.IsIso4217("AED")
fmt.Println(ok) // true
ok, _ = validatorgo.IsIso4217("AE")
fmt.Println(ok) // false
func IsJSON ¶
A validator that checks if the string is valid JSON (note: uses json.Valid()).
ok, _ := validatorgo.IsJSON(`{"name": "John", "age": 30, "city": "New York"}`)
fmt.Println(ok) // true
ok, _ = validatorgo.IsJSON(`{'name': 'John', 'age': 30}`)
fmt.Println(ok) // false
func IsJWT ¶
A validator that checks if the string is valid JWT token.
ok, _ := validatorgo.IsJWT("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c")
fmt.Println(ok) // true
ok, _ = validatorgo.IsJWT("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c")
fmt.Println(ok) // false
func IsLatLong ¶
func IsLatLong(str string, opts *IsLatLongOpts) (bool, error)
A validator that checks if the string is a valid latitude-longitude coordinate in the format lat,long or lat, long.
IsLatLongOpts is a struct that defaults to { CheckDMS: false }.
Pass CheckDMS as true to validate DMS(degrees, minutes, and seconds) latitude-longitude format.
ok, _ := validatorgo.IsLatLong("40.730610,-73.935242" , nil)
fmt.Println(ok) // true
ok, _ = validatorgo.IsLatLong("91,181" , nil)
fmt.Println(ok) // false
func IsLength ¶
func IsLength(str string, opts *IsLengthOpts) (bool, error)
A validator that checks if the string's length falls in a range.
IsLengthOpts is a struct which defaults to { Min: 0, Max: nil }.
Note: this function takes into account surrogate pairs.
ok, _ := validatorgo.IsLength("hello", &validatorgo.IsLengthOpts{Min: 3})
fmt.Println(ok) // true
ok, _ = validatorgo.IsLength("hi", &validatorgo.IsLengthOpts{Min: 3})
fmt.Println(ok) // false
func IsLicensePlate ¶
A validator that checks if the string matches the format of a country's license plate.
locale is one of ("cs-CZ", "de-DE", "de-LI", "en-IN", "en-SG", "en-PK", "es-AR", "hu-HU", "pt-BR", "pt-PT", "sq-AL", "sv-SE", "any")
ok, _ := validatorgo.IsLicensePlate("ABC123", "sv-SE")
fmt.Println(ok) // true
ok, _ = validatorgo.IsLicensePlate("hello", "sv-SE")
fmt.Println(ok) // false
func IsLocale ¶
A validator that checks if the string is a locale.
ok, _ := validatorgo.IsLocale("ca_ES")
fmt.Println(ok) // true
ok, _ = validatorgo.IsLocale("en_XY")
fmt.Println(ok) // false
func IsLowerCase ¶
A validator that checks if the string is lowercase.
ok, _ := validatorgo.IsLowerCase("hello")
fmt.Println(ok) // true
ok, _ = validatorgo.IsLowerCase("WORLD")
fmt.Println(ok) // false
func IsLuhnNumber ¶
A validator that checks if the string passes the Luhn algorithm check.
ok, _ := validatorgo.IsLuhnNumber("4532015112830366")
fmt.Println(ok) // true
ok, _ = validatorgo.IsLuhnNumber("4532015112830367")
fmt.Println(ok) // false
func IsMD5 ¶
A validator that checks if the string is a MD5 hash.
Please note that you can also use the isHash(str, "md5") function.
Keep in mind that MD5 has some collision weaknesses compared to other algorithms (e.g., SHA).
ok, _ := validatorgo.IsMD5("9e107d9d372bb6826bd81d3542a419d6")
fmt.Println(ok) // true
ok, _ = validatorgo.IsMD5("9e107d9d372bb6826bd81d3542a419d")
fmt.Println(ok) // false
func IsMacAddress ¶
func IsMacAddress(str string, opts *IsMacAddressOpts) (bool, error)
A validator that checks if the string is a MAC address.
IsMacAddressOpts is a struct which defaults to { NoSeparators: false, Type: nil }.
If NoSeparators is true, the validator will allow MAC addresses without separators.
Also, it allows the use of hyphens, spaces or dots e.g. "01 02 03 04 05 ab", "01-02-03-04-05-ab" or "0102.0304.05ab".
The Type is a pointer to "48" or "64", defaults to "48"
ok, _ := validatorgo.IsMacAddress("00:1A:2B:3C:4D:5E", nil)
fmt.Println(ok) // true
ok, _ = validatorgo.IsMacAddress("00:1A:2B:3C:4D:ZZ", nil)
fmt.Println(ok) // false
func IsMagnetURI ¶
A validator that checks if the string is a Magnet URI format.
ok, _ := validatorgo.IsMagnetURI("magnet:?xt=urn:btih:123456789abcdef123456789abcdef123456789a")
fmt.Println(ok) // true
ok, _ = validatorgo.IsMagnetURI("magnet:?dn=Example&tr=http://example.com/announce")
fmt.Println(ok) // false
func IsMailtoURI ¶
func IsMailtoURI(str string, opts *IsMailToURIOpts) (bool, error)
A validator that checks if the string is a Mailto URI format.
IsMailToURIOpts is a struct that directly embeds IsEmailOpts.
IsMailToURIOpts validates emails inside the URI (check IsEmailOpts for details).
ok, _ := validatorgo.IsMailtoURI("mailto:[email protected]", nil)
fmt.Println(ok) // true
ok, _ = validatorgo.IsMailtoURI("[email protected]", nil)
fmt.Println(ok) // false
func IsMimeType ¶
A validator that checks if the string matches to a valid MIME type format.
ok, _ := validatorgo.IsMimeType("text/plain")
fmt.Println(ok) // true
ok, _ = validatorgo.IsMimeType("textplain")
fmt.Println(ok) // false
func IsMobilePhone ¶
func IsMobilePhone(str string, locales []string, opts *IsMobilePhoneOpts) (bool, error)
A validator that checks if the string is a mobile phone number.
locale is either a slice of locales e.g. []string{'sk-SK', 'sr-RS'} possible options are ("am-Am", "ar-AE", "ar-BH", "ar-DZ", "ar-EG", "ar-EH", "ar-IQ", "ar-JO", "ar-KW", "ar-PS", "ar-SA", "ar-SD", "ar-SY", "ar-TN", "ar-YE", "az-AZ", "az-LB", "az-LY", "be-BY", "bg-BG", "bn-BD", "bs-BA", "ca-AD", "cs-CZ", "da-DK", "de-AT", "de-CH", "de-DE", "de-LU", "dv-MV", "dz-BT", "el-CY", "el-GR", "en-AG", "en-AI", "en-AU", "en-BM", "en-BS", "en-BW", "en-CA", "en-GB", "en-GG", "en-GH", "en-GY", "en-HK", "en-IE", "en-IN", "en-JM", "en-KE", "en-KI", "en-KN", "en-LS", "en-MO", "en-MT", "en-MU", "en-MW", "en-NG", "en-NZ", "en-PG", "en-PH", "en-PK", "en-RW", "en-SG", "en-SL", "en-SS", "en-TZ", "en-UG", "en-US", "en-ZA", "en-ZM", "en-ZW", "es-AR", "es-BO", "es-CL", "es-CO", "es-CR", "es-CU", "es-DO", "es-EC", "es-ES", "es-GT","es-HN", "es-MX", "es-NI", "es-PA", "es-PE", "es-PY", "es-SV", "es-UY", "es-VE", "et-EE", "fa-AF", "fa-IR", "fi-FI", "fj-FJ", "fo-FO", "fr-BE", "fr-BF", "fr-BJ", "fr-CD", "fr-CF", "fr-FR", "fr-GF", "fr-GP", "fr-MQ", "fr-PF", "fr-RE", "fr-WF", "ga-IE", "he-IL", "hu-HU", "id-ID", "ir-IR", "it-IT", "it-SM", "ja-JP", "ka-GE", "kk-KZ", "kl-GL", "ko-KR", "ky-KG", "lt-LT", "mg-MG", "mn-MN", "ms-MY", "my-MM", "mz-MZ", "nb-NO", "ne-NP", "nl-AW", "nl-BE", "nl-NL", "nn-NO", "pl-PL", "pt-AO", "pt-BR", "pt-PT", "ro-Md", "ro-RO", "ru-RU", "si-LK", "sk-SK", "sl-SI", "so-SO", "sq-AL", "sr-RS", "sv-SE", "tg-TJ", "th-TH", "tk-TM", "tr-TR", "uk-UA", "uz-UZ", "vi-VN", "zh-CN", "zh-HK", "zh-MO", "zh-TW"). If nil is provided any of the locales will be matched. If an unidentified value is used, function will return false.
IsMobilePhoneOpts is a struct that can be supplied with the following keys:
StrictMode, if this is set to true, the mobile phone number must be supplied with the country code and therefore must start with +.
ok, _ := validatorgo.IsMobilePhone("08070448986", []string{"en-US"} , nil)
fmt.Println(ok) // true
ok, _ = validatorgo.IsMobilePhone("090666666567", []string{"en-US"} , nil)
fmt.Println(ok) // false
func IsMongoID ¶
A validator that checks if the string is a valid hex-encoded representation of a MongoDB ObjectId.
ok, _ := validatorgo.IsMongoID("507f1f77bcf86cd799439011")
fmt.Println(ok) // true
ok, _ = validatorgo.IsMongoID("507f1f77bcf86cd79943901")
fmt.Println(ok) // false
func IsMultibyte ¶
A validator that checks if the string contains one or more multibyte chars.
ok, _ := validatorgo.IsMultibyte("こんにちは")
fmt.Println(ok) // true
ok, _ = validatorgo.IsMultibyte("hello")
fmt.Println(ok) // false
func IsNumeric ¶
func IsNumeric(str string, opts *IsNumericOpts) (bool, error)
A validator that check if a string is a number.
IsNumericOpts is a struct which defaults to { NoSymbols: false, Locale: ""}.
If NoSymbols is true, the validator will reject numeric strings that feature a symbol (e.g. +, -, or .).
Locale determines the numeric format and is one of ("ar", "ar-AE", "ar-BH", "ar-DZ", "ar-EG", "ar-IQ", "ar-JO", "ar-KW", "ar-LB", "ar-LY", "ar-MA", "ar-QA", "ar-QM", "ar-SA", "ar-SD", "ar-SY", "ar-TN", "ar-YE", "bg-BG", "cs-CZ", "da-DK", "de-DE", "en-AU", "en-GB", "en-HK", "en-IN", "en-NZ", "en-US", "en-ZA", "en-ZM", "eo", "es-ES", "fr-FR", "fr-CA", "hu-HU", "it-IT", "nb-NO", "nl-NL", "nn-NO", "pl-PL", "pt-BR", "pt-PT", "ru-RU", "sl-SI", "sr-RS", "sr-RS@latin", "sv-SE", "tr-TR", "uk-UA"). Locale will default to "en-US" if not present.
ok, _ := validatorgo.IsNumeric("12345", nil)
fmt.Println(ok) // true
ok, _ = validatorgo.IsNumeric("12.34.56", nil)
fmt.Println(ok) // false
func IsObject ¶
func IsObject(str string, opts *IsObjectOpts) (bool, error)
A validator to check that a value is a json object. For example, "{}", "{ foo: 'bar' }" would pass this validator.
IsObjectOpts is a struct which defaults to { Strict: true }.
If the Strict option is set to false, then this validator works, where both arrays ("[]") and the null ("null") value are considered objects.
ok, _ := validatorgo.IsObject(`{"name": "John", "age": 30}`, &validatorgo.IsObjectOpts{Strict: true})
fmt.Println(ok) // true
ok, _ = validatorgo.IsObject(`{"name": "John", "age`, &validatorgo.IsObjectOpts{Strict: true})
fmt.Println(ok) // false
func IsOctal ¶
A validator that checks if the string is a valid octal number.
ok, _ := validatorgo.IsOctal("07")
fmt.Println(ok) // true
ok, _ = validatorgo.IsOctal("078")
fmt.Println(ok) // false
func IsPassportNumber ¶
A validator that checks if the string is a valid passport number.
countryCode is one of ("AM", "AR", "AT", "AU", "AZ", "BE", "BG", "BY", "BR", "CA", "CH", "CN", "CY", "CZ", "DE", "DK", "DZ", "EE", "ES", "FI", "FR", "GB", "GR", "HR", "HU", "IE", "IN", "IR", "ID", "IS", "IT", "JM", "JP", "KR", "KZ", "LI", "LT", "LU", "LV", "LY", "MT", "MX", "MY", "MZ", "NL", "NZ", "PH", "PK", "PL", "PT", "RO", "RU", "SE", "SL", "SK", "TH", "TR", "UA", "US", "ZA").
ok, _ := validatorgo.IsPassportNumber("123456789", "US")
fmt.Println(ok) // true
ok, _ = validatorgo.IsPassportNumber("A12345678", "US")
fmt.Println(ok) // false
func IsPort ¶
A validator that checks if the string is a valid port number.
ok, _ := validatorgo.IsPort("07")
fmt.Println(ok) // true
ok, _ = validatorgo.IsPort("078")
fmt.Println(ok) // false
func IsPostalCode ¶
A validator that checks if the string is a postal code.
locale is one of ("AD", "AT", "AU", "AZ", "BA", "BE", "BG", "BR", "BY", "CA", "CH", "CN", "CO", "CZ", "DE", "DK", "DO", "DZ", "EE", "ES", "FI", "FR", "GB", "GR", "HR", "HT", "HU", "ID", "IE", "IL", "IN", "IR", "IS", "IT", "JP", "KE", "KR", "LI", "LK", "LT", "LU", "LV", "MG", "MT", "MX", "MY", "NL", "NO", "NP", "NZ", "PL", "PR", "PT", "RO", "RU", "SA", "SE", "SG", "SI", "SK", "TH", "TN", "TW", "UA", "US", "ZA", "ZM"). If "any" or no locale is used, function will check if any of the locales match.
ok, _ := validatorgo.IsPostalCode("90210", "US")
fmt.Println(ok) // true
ok, _ = validatorgo.IsPostalCode("902101", "DE")
fmt.Println(ok) // false
func IsRFC3339 ¶
A validator that checks if the string is a valid RFC 3339 date.
ok, _ := validatorgo.IsRFC3339("2024-09-21T14:30:00Z")
fmt.Println(ok) // true
ok, _ = validatorgo.IsRFC3339("2024-09-21 14:30:00Z")
fmt.Println(ok) // false
func IsRgbColor ¶
A validator that checks if the string is a rgb or rgba color.
IsRgbOpts is a struct with the following properties:
IncludePercentValues defaults to false. If you don't want to allow to set rgb or rgba values with percents, like rgb(5%,5%,5%), or rgba(90%,90%,90%,.3), then set it to false.
AllowSpaces defaults to false, which prohibits whitespace. If set to false, whitespace between color values is allowed, such as rgb(255, 255, 255) or even rgba(255, 128, 0, 0.7).
ok, _ := validatorgo.IsRgbColor("rgb(255,0,0)", nil)
fmt.Println(ok) // true
ok, _ = validatorgo.IsRgbColor("rgb( 255 , 0 , 0 )", nil)
fmt.Println(ok) // false
func IsSemVer ¶
A validator that checks if the string is a Semantic Versioning Specification (SemVer).
ok, _ := validatorgo.IsSemVer("1.0.0")
fmt.Println(ok) // true
ok, _ = validatorgo.IsSemVer("1.0.0.0")
fmt.Println(ok) // false
func IsSlug ¶
A validator that checks if the string is of type slug.
ok, _ := validatorgo.IsSlug("rgb(255,0,0)")
fmt.Println(ok) // true
ok, _ = validatorgo.IsSlug("rgb( 255 , 0 , 0 )")
fmt.Println(ok) // false
func IsStrongPassword ¶
func IsStrongPassword(str string, opts *IsStrongPasswordOpts) (bool, float64, error)
A validator that checks if the string can be considered a strong password or not. Returns the validity and the score.
Default IsStrongPasswordOpts: { MinLength: 8, MinLowercase: 1, MinUppercase: 1, MinNumbers: 1, MinSymbols: 1, PointsPerUnique: 1, PointsPerRepeat: 0.5, PointsForContainingLower: 10, PointsForContainingUpper: 10, PointsForContainingNumber: 10, PointsForContainingSymbol: 10 }
ok, _, _ := validatorgo.IsStrongPassword("Password123!", nil)
fmt.Println(ok) // true
ok, _, _ = validatorgo.IsStrongPassword("P@ss1", nil)
fmt.Println(ok) // false
func IsSurrogatePair ¶
A validator that checks if the string contains any surrogate pairs chars.
ok, _ := validatorgo.IsSurrogatePair("")
fmt.Println(ok) // true
ok, _ = validatorgo.IsSurrogatePair("")
fmt.Println(ok) // false
func IsTaxID ¶
A validator that checks if the string is a valid Tax Identification Number. Defaults locale is "en-US" and "any" will match any of them.
Supported locales: ("bg-BG", "cs-CZ", "de-AT", "de-DE", "dk-DK", "el-CY", "el-GR", "en-CA", "en-GB", "en-IE", "en-US", "es-AR", "es-ES", "et-EE", "fi-FI", "fr-BE", "fr-CA", "fr-FR", "fr-LU", "hr-HR", "hu-HU", "it-IT", "lb-LU", "lt-LT", "lv-LV", "mt-MT", "nl-BE", "nl-NL", "pl-PL", "pt-BR", "pt-PT", "ro-RO", "sk-SK", "sl-SI", "sv-SE", "uk-UA").
func IsTime ¶
func IsTime(str string, opts *IsTimeOpts) (bool, error)
A validator that checks if the string is a valid time e.g. 23:01:59
IsTimeOpts is a struct which can contain the keys HourFormat and Mode.
HourFormat is a key and defaults to "hour24".
Mode is a key and defaults to "default".
HourFormat can contain the values "hour12" or "hour24", "hour24" will validate hours in 24 format and "hour12" will validate hours in 12 format.
Mode can contain the values "default" or "withSeconds", "default" will validate HH:MM or HH:MM:SS format, "withSeconds" will validate only HH:MM:SS format.
ok, _ := validatorgo.IsTime("14:30", nil)
fmt.Println(ok) // true
ok, _ = validatorgo.IsTime("09:5", nil)
fmt.Println(ok) // false
func IsULID ¶
A validator that checks if the string is a ULID.
ok, _ := validatorgo.IsULID("01ARZ3NDEKTSV4RRFFQ69G5FAV")
fmt.Println(ok) // true
ok, _ = validatorgo.IsULID("01ARZ3NDEKTSV4RRFFQ69G5FA")
fmt.Println(ok) // false
func IsURL ¶
A validator that checks if the string is a URL.
IsURLOpts is a struct which defaults to { Protocols: []string{"https","http","ftp"}, RequireTld: true, RequireProtocol: false, RequireHost: true, RequirePort: false, RequireValidProtocol: true, AllowUnderscores: false, HostWhitelist: nil, HostBlacklist: nil, AllowTrailingDot: false, AllowProtocolRelativeUrls: true, AllowFragments: true, AllowQueryComponents: true, DisallowAuth: false, ValidateLength: true, MaxAllowedLength:: 2048 }.
RequireProtocol - if set to true IsURL will return false if protocol is not present in the URL.
RequireValidProtocol - IsURL will check if the URL's protocol is present in the protocols option.
protocols - valid protocols can be modified with this option.
RequireHost - if set to false IsURL will not check if host is present in the URL.
RequirePort - if set to true IsURL will check if port is present in the URL.
AllowProtocolRelativeUrls - if set to true protocol relative URLs will be allowed.
AllowFragments - if set to false IsURL will return false if fragments are present.
AllowQueryComponents - if set to false IsURL will return false if query components are present.
ValidateLength - if set to false IsURL will skip string length validation. MaxAllowedLength will be ignored if this is set as false.
MaxAllowedLength - if set IsURL will not allow URLs longer than the specified value (default is 2084 that IE maximum URL length).
ok, _ := validatorgo.IsURL("http://localhost", &validatorgo.IsURLOpts{RequireTld: Bool(false), AllowProtocolRelativeUrls: Bool(true)})
fmt.Println(ok) // true
ok, _ = validatorgo.IsURL("example.com", &validatorgo.IsURLOpts{RequireProtocol: Bool(true), AllowProtocolRelativeUrls: Bool(true)})
fmt.Println(ok) // false
func IsUUID ¶
A validator that checks if the string is an RFC9562 UUID.
version is one of ("1"-"5"). if none is not provided, it will validate any of them.
ok, _ := validatorgo.IsUUID("550e8400-e29b-11d4-a716-446655440000", "1")
fmt.Println(ok) // true
ok, _ = validatorgo.IsUUID("f47ac10b-58cc-4372-a567-0e02b2c3d479", "1")
fmt.Println(ok) // false
func IsUpperCase ¶
A validator that checks if the string is uppercase.
ok, _ := validatorgo.IsUpperCase("HELLO")
fmt.Println(ok) // true
ok, _ = validatorgo.IsUpperCase("world")
fmt.Println(ok) // false
func IsVAT ¶
A validator that checks if the string is a valid VAT number if validation is available for the given country code matching ISO 3166-1 alpha-2.
countryCode is one of ("AL", "AR", "AT", "AU", "BE", "BG", "BO", "BR", "BY", "CA", "CH", "CL", "CO", "CR", "CY", "CZ", "DE", "DK", "DO", "EC", "EE", "EL", "ES", "FI", "FR", "GB", "GT", "HN", "HR", "HU", "ID", "IE", "IL", "IN", "IS", "IT", "KZ", "LT", "LU", "LV", "MK", "MT", "MX", "NG", "NI", "NL", "NO", "NZ", "PA", "PE", "PH", "PL", "PT", "PY", "RO", "RS", "RU", "SA", "SE", "SI", "SK", "SM", "SV", "TR", "UA", "UY", "UZ", "VE"). If no value or "any" is provided will match every one.
ok, _ := validatorgo.IsVAT("DE123456789", "DE")
fmt.Println(ok) // true
ok, _ = validatorgo.IsVAT("DE12345678", "DE")
fmt.Println(ok) // false
func IsVariableWidth ¶
A validator that checks if the string contains a mixture of full and half-width chars.
ok, _ := validatorgo.IsVariableWidth("abc123")
fmt.Println(ok) // true
ok, _ = validatorgo.IsVariableWidth("abc123")
fmt.Println(ok) // false
func IsWhitelisted ¶
A validator that checks if the string consists only of characters that appear in the whitelist chars.
ok, _ := validatorgo.IsWhitelisted("stop", "post")
fmt.Println(ok) // true
ok, _ = validatorgo.IsWhitelisted("bang", "take")
fmt.Println(ok) // false
func Matches ¶
A validator that checks if the string matches the regex.
ok, _ := validatorgo.Matches("foo", regexp.MustCompile(`^foo$`))
fmt.Println(ok) // true
ok, _ = validatorgo.Matches("foo", regexp.MustCompile(`^foobar$`))
fmt.Println(ok) // false
Types ¶
type ContainsOpt ¶
type ContainsOpt struct {
IgnoreCase *bool // ignore case when doing comparison, default false.
MinOccurrences *int // minimum number of occurrences for the seed in the string. Defaults to 1.
}
ContainsOpt is used to configure Contains
type DecimalDigits ¶
type DecimalDigits struct {
Min *uint // minimum allowed decimal range
Max *uint // maximum allowed decimal range
}
DecimalDigits is used to configure IsDecimalOpts
type IsAfterOpts ¶
type IsAfterOpts struct {
ComparisonDate *string // date to be compared to. Valid layouts are from the time package e.g Layout, ANSIC, UnixDate, RubyDate, RFC822, RFC822Z, RFC850, RFC1123, RFC1123Z, Kitchen, Stamp, StampMilli, StampMicro, StampNano, DateTime, DateOnly, TimeOnly, StandardDateLayout, SlashDateLayout, DateTimeLayout, ISO8601Layout, ISO8601ZuluLayout, ISO8601WithMillisecondsLayout.
}
IsAfterOpts is used to configure IsAfter
type IsAlphaOpts ¶
IsAlphaOpts is used to configure IsAlpha
type IsAlphanumericOpts ¶
type IsAlphanumericOpts struct {
Ignore *string // string to be ignored
Locale *string // a locale
}
IsAlphanumericOpts is used to configure IsAlphanumeric
type IsArrayOpts ¶
IsArrayOpts is used to configure IsArray
type IsBase32Opts ¶
type IsBase32Opts struct {
Crockford *bool // whether to use crockfords base32 alternative encoding scheme
}
IsBase32Opts is used to configure IsBase32
type IsBase64Opts ¶
type IsBase64Opts struct {
UrlSafe *bool // checks whether string is url safe.
}
IsBase64Opts is used to configure IsBase64
type IsBeforeOpts ¶
type IsBeforeOpts struct {
ComparisonDate *string // date to be compared to. Valid layouts are from the time package e.g LLayout, ANSIC, UnixDate, RubyDate, RFC822, RFC822Z, RFC850, RFC1123, RFC1123Z, Kitchen, Stamp, StampMilli, StampMicro, StampNano, DateTime, DateOnly, TimeOnly, StandardDateLayout, SlashDateLayout, DateTimeLayout, ISO8601Layout, ISO8601ZuluLayout, ISO8601WithMillisecondsLayout.
}
IsBeforeOpts is used to configure IsBefore
type IsBooleanOpts ¶
type IsBooleanOpts struct {
Loose *bool // strictness of the equality
}
IsBooleanOpts is used to configure IsBoolean
type IsByteLengthOpts ¶
IsByteLengthOpts is used to configure IsByteLength
type IsCreditCardOpts ¶
type IsCreditCardOpts struct {
Provider *string // credit card issuer
}
IsCreditCardOpts is used to configure IsCreditCard
type IsCurrencyOpts ¶
type IsCurrencyOpts struct {
// deals with the options for currency
Symbol *string // '$10.50'
RequireSymbol *bool // $10.50
AllowSpaceAfterSymbol *bool // $ 10.50
SymbolAfterDigits *bool // 10.50$
// deals with the numeric signs
AllowNegatives *bool // -$10.50
ParensForNegatives *bool // ($10.50)
NegativeSignBeforeDigits *bool // $-10.50
NegativeSignAfterDigits *bool // $10.50-
AllowNegativeSignPlaceholder *bool // $ 10.50
// deals with the decimals/separator
ThousandSeparator *string // 10,000.50
DecimalSeparator *string // 10.50
AllowDecimal *bool // $10.00
RequireDecimal *bool // $10.00
MaxDigitsAfterDecimal *uint // $10.50
AllowSpaceAfterDigits *bool // '$ 10.50
}
type IsDateOpts ¶
IsDateOpts is used to configure IsDate
type IsDecimalOpts ¶
type IsDecimalOpts struct {
DecimalDigits
ForceDecimal *bool // decimal/radix point must be present
Locale *string // locale used
}
IsDecimalOpts is used to configure IsDecimal
type IsEmailOpts ¶
type IsEmailOpts struct {
AllowDisplayName *bool
RequireDisplayName *bool
AllowUTF8LocalPart *bool
RequireTld *bool
IgnoreMaxLength *bool
AllowIpDomain *bool
DomainSpecificValidation *bool
BlacklistedChars *string
HostBlacklist []string
HostWhitelist []string
}
IsEmailOpts is used to configure IsEmail
type IsEmptyOpts ¶
type IsEmptyOpts struct {
IgnoreWhitespace *bool
}
IsEmptyOpts is used to configure IsEmpty
type IsFQDNOpts ¶
type IsFQDNOpts struct {
RequireTld *bool
AllowUnderscores *bool
AllowTrailingDot *bool
AllowNumericTld *bool
IgnoreMaxLength *bool
}
IsFQDNOptsOpts is used to configure IsFQDNOpts
type IsFloatOpts ¶
type IsIMEIOpts ¶
type IsIMEIOpts struct {
AllowHyphens *bool
}
IsIMEIOpts is used to configure IsIMEI
type IsISO8601Opts ¶
type IsISO8601Opts struct {
Strict *bool // must be a date that has actually happened, is happening or will happen.
StrictSeparator *bool // must be delimited by T
}
IsISO8601Opts is used to configure IsISO8601
type IsISSNOpts ¶
type IsISSNOpts struct {
RequireHyphen *bool // requires a hyphen
CaseSensitive *bool // must be exact case
}
IsISSNOpts is used to configure IsISSN
type IsLatLongOpts ¶
type IsLatLongOpts struct {
CheckDMS *bool // checks DMS(degrees, minutes, and seconds)
}
IsLatLongOpts is used to configure IsLatLong
type IsLengthOpts ¶
type IsLengthOpts struct {
Min *uint // Minimum character length
Max *uint // Maximum character length
}
IsLengthOpts is used to configure IsLength
type IsMacAddressOpts ¶
type IsMacAddressOpts struct {
NoSeparators *bool // will not allow separators
Type *string // mac address type
}
IsMacAddressOpts is used to configure IsMacAddress
type IsMailToURIOpts ¶
type IsMailToURIOpts struct {
IsEmailOpts
}
IsMailToURIOpts is used to configure IsMailtoURI
type IsMobilePhoneOpts ¶
type IsMobilePhoneOpts struct {
StrictMode *bool // matches format exactly
}
IsMobilePhoneOpts is used to configure IsMobilePhone
type IsNumericOpts ¶
IsNumericOpts is used to configure IsNumeric
type IsObjectOpts ¶
type IsObjectOpts struct {
Strict *bool // looseness or strictness
}
IsObjectOpts is used to configure IsObject
type IsRgbOpts ¶
type IsRgbOpts struct {
IncludePercentValues *bool // must use percent values 90% not 0-255
AllowSpaces *bool // whether to include spaces
}
IsRgbOpts is used to configure IsRgbColor
type IsStrongPasswordOpts ¶
type IsStrongPasswordOpts struct {
MinLength *int // passwords minimum length
MinLowercase *int // passwords minimum lowercase letters
MinUppercase *int // passwords minimum uppercase letters
MinNumbers *int // passwords minimum numbers
MinSymbols *int // passwords minimum symbols
PointsPerUnique *float64 // minimum points per unique character
PointsPerRepeat *float64 // minimum points per repeated character
PointsForContainingLower *float64 // minimum points per lowercase character
PointsForContainingUpper *float64 // minimum points per uppercase character
PointsForContainingNumber *float64 // minimum points per numeric character
PointsForContainingSymbol *float64 // minimum points per special character
}
IsStrongPasswordOpts is used to configure IsStrongPassword
type IsTimeOpts ¶
type IsURLOpts ¶
type IsURLOpts struct {
Protocols []string
RequireTld *bool
RequireProtocol *bool
RequireHost *bool
RequirePort *bool
RequireValidProtocol *bool
AllowUnderscores *bool
HostWhitelist []string
HostBlacklist []string
AllowTrailingDot *bool
AllowProtocolRelativeUrls *bool
AllowFragments *bool
AllowQueryComponents *bool
DisallowAuth *bool
ValidateLength *bool
MaxAllowedLength *int
}
type ValidationError ¶ added in v1.0.0
type ValidationError struct {
// Validator is the name of the validator function that failed (e.g., "IsEmail").
Validator string
// Code is a machine-readable error code (e.g., ErrInvalidFormat).
Code string
// Message is a human-readable description of the failure.
Message string
}
ValidationError represents a validation failure with context about why it failed.
func (*ValidationError) Error ¶ added in v1.0.0
func (e *ValidationError) Error() string
Error implements the error interface.
Source Files
¶
- contains.go
- equals.go
- errors.go
- isabarouting.go
- isafter.go
- isalpha.go
- isalpha_locales.go
- isalphanum.go
- isarray.go
- isascii.go
- isbase32.go
- isbase58.go
- isbase64.go
- isbefore.go
- isbic.go
- isboolean.go
- isbtcaddress.go
- isbytelength.go
- iscountrycode.go
- iscreditcard.go
- iscurrency.go
- isdatauri.go
- isdate.go
- isdecimal.go
- isdecimal_formats.go
- isdivisibleby.go
- isean.go
- isemail.go
- isempty.go
- isetheruemaddress.go
- isfloat.go
- isfqdn.go
- isfreightcontainerid.go
- isfullwidth.go
- ishalfwidth.go
- ishash.go
- ishexadecimal.go
- ishexcolor.go
- ishsl.go
- isiban.go
- isidentitycard.go
- isimei.go
- isin.go
- isint.go
- isip.go
- isiprange.go
- isisbn.go
- isisin.go
- isiso31661alpha2.go
- isiso31661alpha3.go
- isiso31661numeric.go
- isiso4217.go
- isiso6346.go
- isiso6391.go
- isiso8601.go
- isisrc.go
- isissn.go
- isjson.go
- isjwt.go
- islatlong.go
- islength.go
- islicenseplate.go
- islocale.go
- islowercase.go
- isluhnnumber.go
- ismacaddress.go
- ismagneturi.go
- ismailtouri.go
- ismd5str.go
- ismimetype.go
- ismobilephone.go
- ismobilephone_locales.go
- ismongoid.go
- ismultibyte.go
- isnumeric.go
- isnumeric_formats.go
- isobject.go
- isoctal.go
- ispassport.go
- isport.go
- ispostalcode.go
- isrfc3339.go
- isrgbcolor.go
- issemver.go
- isslug.go
- isstrongpassword.go
- issurrogatepair.go
- istaxid.go
- istime.go
- isulid.go
- isuppercase.go
- isurl.go
- isuuid.go
- isvariablewidth.go
- isvat.go
- iswhilelisted.go
- matches.go
- opts.go
- regexcache.go
- utils.go