A library of string validators and sanitizers, based on the js library validator.js
Why should not you use other widely known Go libraries like go-playground/validator or asaskevich/govalidator. The reason is that these libraries primarily focus on validating structs rather than standalone strings. Additionally, they lack a comprehensive library of validators comparable to the original js package validator.js, on which they are based.
I created this project to serve as a dependency for another Go open-source library I developed, called ginvalidator. ginvalidator is designed specifically for validating HTTP requests and acts as the Go equivalent of the popular Node.js/Express library express-validator.
The existing libraries in the Go ecosystem were either too complex, not robust enough, or unsuitable for my use case. That’s why I decided to build my own library.
Using go get.
go get -u github.com/bube054/validatorgo
Then import the package into your own code.
import (
"fmt"
"github.com/bube054/validatorgo"
)
If you are unhappy using the long validatorgo package name, you can do this.
import (
"fmt"
vgo "github.com/bube054/validatorgo"
)
func main(){
id := "5f2a6c69e1d7a4e0077b4e6b"
validId := vgo.IsMongoID(id)
fmt.Println(validId) // true
}
Here is a list of the validators currently available.
Validator | Description |
---|---|
Contains(str, seed string, opts *ContainsOpt) | A validator that checks if a string contains a seed. ContainsOpt defaults to { IgnoreCase: false, MinOccurrences: 1 } . ContainsOpt: - IgnoreCase : Ignore case during comparison (default: false ). - MinOccurrences : Minimum number of occurrences for the seed in the string (default: 1 ). |
Equals(str string, comparison string)) | A validator that checks if the string matches the comparison. |
IsAbaRouting(str string) | A validator that checks if the string is an ABA routing number for US bank account / cheque. |
IsAfter(str string, opts *IsAfterOpts) | 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 . |
IsAlpha(str string, opts *IsAlphaOpts) | 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. |
IsAlphanumeric(str string, opts *IsAlphanumericOpts) | 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 : 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 if none is provided. |
IsArray(str string, opts *IsArrayOpts) | 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 . |
IsAscii(str string) | A validator that checks if the string contains ASCII chars only. |
IsBase32(str string, opts *IsBase32Opts) | 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. |
IsBase58(str string) bool | A validator that checks if the string is base58 encoded. |
IsBase64(str string, opts *IsBase64Opts) | 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. |
IsBefore(str string, opts *IsBeforeOpts) | A validator that checks if the string is a date that is before 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. . |
IsBic(str string) | A validator that checks if the string is a BIC (Bank Identification Code) or SWIFT code. |
IsBoolean(str string, opts *IsBooleanOpts) | A validator that check if the string is a boolean. |
IsBTCAddress(str string) | A validator that checks if the string is a valid BTC address. |
IsByteLength(str string, opts *IsByteLengthOpts) | 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 } . |
IsCreditCard(str string, opts *IsCreditCardOpts) | 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. |
IsCurrency(str string, opts *IsCurrencyOpts) | 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 } . |
IsDataURI(str string) | A validator that checks if the string is a data uri format. |
IsDate(str string, opts *IsDateOpts) | 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. |
IsDecimal(str string, opts *IsDecimalOpts) | 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 |
IsDivisibleBy(str string, num int) | 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). |
IsEAN(str string) | IsEAN checks if the string is a valid EAN (European Article Number). |
IsEmail(str string, opts *IsEmailOpts) | 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, DomainSpecificValidation: false, BlacklistedChars: "", HostBlacklist: [] } . AllowDisplayName : if set to true, the validator will also match Display Name . RequireDisplayName : if set to true, the validator will reject strings without the format Display Name . 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. |
IsEmpty(str string, opts *IsEmptyOpts) | A validator check if the string has a length of zero. IsEmptyOpts is a struct which defaults to { IgnoreWhitespace: false } . |
IsEthereumAddress(str string) | A validator checks if the string is an Ethereum address. Does not validate address checksums. |
IsFloat(str string, opts *IsFloatOpts) | 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") |
IsFQDN(str string, opts *IsFQDNOpts) | 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 } |
IsFreightContainerID(str string) | A validator that checks alias for IsISO6346, check if the string is a valid ISO 6346 shipping container identification. |
IsFullWidth(str string) | A validator that checks if the string contains any full-width chars. |
IsHalfWidth(str string) | A validator that checks if the string contains any half-width chars. |
IsHash(str, algorithm string) | 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")'ripemd128', 'ripemd160', 'sha1', 'sha256', 'sha384', 'sha512', 'tiger128', 'tiger160', 'tiger192') , No checksum are calculated. |
IsHexadecimal(str string) | A validator that checks if the string is a hexadecimal number. |
IsHexColor(str string) | A validator that checks if the string is a hexadecimal color. |
IsHSL(str string) | A validator that checks if the string is an HSL (hue, saturation, lightness, optional alpha) color based on CSS Colors Level 4 specification. |
IsIBAN(str, countryCode string) | 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. |
IsIdentityCard(str, locale string) | 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. |
IsIMEI(str string, opts *IsIMEIOpts) | 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. |
IsIn(str string, values []string) | A validator that checks if the string is in a slice of allowed values. |
IsInt(str string, opts *IsIntOpts) | 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). |
IsIP(str, version string) | 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. |
IsIPRange(str, version string) | 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. |
IsISBN(str, version string) | 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. |
IsISIN(str string) | A validator that checks if the string is an ISIN (stock/security identifier). |
IsIso4217(str string) | A validator that checks if the string is a valid ISO 4217 officially assigned currency code. |
IsISO6346(str string) | A validator that checks if the string is a valid ISO 6346 shipping container identification. |
IsISO6391(str string) | A validator that checks if the string is a valid ISO 639-1 language code. |
IsISO6391(str string) | A validator that checks if the string is a valid ISO 639-1 language code. |
IsISO8601(str string, opts *IsISO8601Opts) | 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. |
IsISO31661Alpha2(str string) | A validator that checks if the string is a valid ISO 3166-1 alpha-2 officially assigned country code. |
IsISO31661Alpha3(str string) | A validator that checks if the string is a valid ISO 3166-1 alpha-3 officially assigned country code. |
IsISO31661Numeric(str string) | A validator that checks check if the string is a valid ISO 3166-1 numeric officially assigned country code. |
IsISRC(str string, allowHyphens bool) | A validator that checks if the string is an ISRC. allowHyphens will allow codes with dashes present CC-XXX-YY-NNNNN |
IsISSN(str string, opts *IsISSNOpts) | 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. |
IsJSON(str string) | A validator that checks if the string is valid JSON (note: uses json.Valid() ). |
IsLatLong(str string, opts *IsLatLongOpts) | 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. |
IsLicensePlate(str string, locale string) | 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") |
IsLocale(str string) | A validator that checks if the string is a locale. |
IsLowerCase(str string) | A validator that checks if the string is lowercase. |
IsLuhnNumber(str string) | A validator that checks if the string passes the Luhn algorithm check. |
IsMacAddress(str string, opts *IsMacAddressOpts) | 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" |
IsMagnetURI(str string) | A validator that checks if the string is a Magnet URI format. |
IsMailtoURI(str string, opts *IsMailToURIOpts) | 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). |
IsMD5(str string) | 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). |
IsMimeType(str string) | A validator that checks if the string matches to a valid MIME type format. |
IsMobilePhone(str string, locales []string, opts *IsMobilePhoneOpts) | 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 +. |
IsMongoID(str string) | A validator that checks if the string is a valid hex-encoded representation of a MongoDB ObjectId. |
IsMultibyte(str string) | A validator that checks if the string contains one or more multibyte chars. |
IsNumeric(str string, opts *IsNumericOpts) | 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. |
F(str string, opts *IsObjectOpts) | 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. |
IsOctal(str string) | A validator that checks if the string is a valid octal number. |
IsPassportNumber(str, countryCode string) | 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") . |
IsPort(str string) | A validator that checks if the string is a valid port number. |
IsPostalCode(str, locale string) | 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. |
IsRFC3339(str string) | A validator that checks if the string is a valid RFC 3339 date. |
IsRgbColor(str string, opts *IsRgbOpts) | 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). |
IsSemVer(str string) | A validator that checks if the string is a Semantic Versioning Specification (SemVer). |
IsSlug(str string) | A validator that checks if the string is of type slug. |
IsStrongPassword(str string, opts *IsStrongPasswordOpts) | 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 } , note all values here are pointers. |
IsSurrogatePair(str string) | A validator that checks if the string contains any surrogate pairs chars. |
IsTaxID(str, locale string) | 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") . |
IsTime(str string, opts IsTimeOpts) | 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. |
IsULID(str string) | A validator that checks if the string is a ULID. |
IsUpperCase(str string) | A validator that checks if the string is uppercase. |
IsURL(str string, opts *IsURLOpts) | 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. |
IsUUID(str, version string) | 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. 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). |
IsVariableWidth(str string) | A validator that checks if the string contains a mixture of full and half-width chars. |
IsVAT(str, countryCode string) | 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. |
IsWhitelisted(str, chars string) | A validator that checks if the string consists only of characters that appear in the whitelist chars. |
Matches(str string, re *regexp.Regexp) | A validator that checks if the string matches the regex. |
⚠ Caution
When using a validator that requires an options struct (either a pointer or non-pointer), always provide values for all the struct fields explicitly. Unlike in validator.js, where missing fields are automatically set to defaults, Go uses strict types. This means missing values will default to false for booleans, 0 for number types, etc. Not specifying all fields could lead to unexpected behavior if you're used to the JavaScript version.
Examples
// do this (using the default options specified in the docs)
ok := validatorgo.IsFQDN("example", nil)
// or this (explicitly setting all possible fields for the structs)
ok := validatorgo.IsFQDN("example", &validatorgo.IsFQDNOpts{
RequireTld: false,
AllowUnderscores: false,
AllowTrailingDot: true,
AllowNumericTld: false,
IgnoreMaxLength: true
})
// but rarely this(not explicitly setting all possible fields)
ok := validatorgo.IsFQDN("example", &validatorgo.IsFQDNOpts{ RequireTld: false, })
import (
"fmt"
"github.com/bube054/validatorgo/sanitizer"
)
func main(){
str := sanitizer.Whitelist("Hello123 World!", "a-zA-Z")
fmt.Println(str) // "HelloWorld"
}
Here is a list of the sanitizers currently available.
Sanitizer | Description |
---|---|
Blacklist(str, blacklistedChars string) | A sanitizer that remove characters that appear in the blacklist. The characters are used in a RegExp and will escaped for you. |
Escape(str string) | A sanitizer that replaces <, >, &, ' and ". with HTML entities. |
LTrim(str, chars string) | A sanitizer that trims characters (whitespace by default) from the left-side of the input. |
NormalizeEmail(email string, opts *NormalizeEmailOpts) | A sanitizer that canonicalizes an email address. (This doesn't validate that the input is an email, if you want to validate the email use IsEmail beforehand). NormalizeEmailOpts is a struct with the following keys and default values: AllLowercase : true - Transforms the local part (before the @ symbol) of all email addresses to lowercase. Please note that this may violate RFC 5321, which gives providers the possibility to treat the local part of email addresses in a case sensitive way (although in practice most - yet not all - providers don't). The domain part of the email address is always lowercased, as it is case insensitive per RFC 1035. GmailLowercase : true - Gmail addresses are known to be case-insensitive, so this switch allows lowercasing them even when AllLowercase is set to false . Please note that when AllLowercase is true , Gmail addresses are lowercased regardless of the value of this setting. GmailRemoveDots : true: Removes dots from the local part of the email address, as Gmail ignores them (e.g. "john.doe" and "johndoe" are considered equal). GmailRemoveSubaddress : true : Normalizes addresses by removing "sub-addresses", which is the part following a "+" sign (e.g. "[email protected]" becomes "[email protected]"). GmailConvertGooglemaildotcom : true: Converts addresses with domain @googlemail.com to @gmail.com, as they're equivalent. OutlookdotcomLowercase : true - Outlook.com addresses (including Windows Live and Hotmail) are known to be case-insensitive, so this switch allows lowercasing them even when AllLowercase is set to false . Please note that when AllLowercase is true , Outlook.com addresses are lowercased regardless of the value of this setting. OutlookdotcomRemoveSubaddress : true : Normalizes addresses by removing "sub-addresses", which is the part following a "+" sign (e.g. "[email protected]" becomes "[email protected]"). YahooLowercase : true - Yahoo Mail addresses are known to be case-insensitive, so this switch allows lowercasing them even when AllLowercase is set to false . Please note that when AllLowercase is true , Yahoo Mail addresses are lowercased regardless of the value of this setting. YahooRemoveSubaddress : true : Normalizes addresses by removing "sub-addresses", which is the part following a "-" sign (e.g. "[email protected]" becomes "[email protected]"). IcloudLowercase : true - iCloud addresses (including MobileMe) are known to be case-insensitive, so this switch allows lowercasing them even when AllLowercase is set to false. Please note that when AllLowercase is true, iCloud addresses are lowercased regardless of the value of this setting. IcloudRemoveSubaddress : true : Normalizes addresses by removing "sub-addresses", which is the part following a "+" sign (e.g. "[email protected]" becomes "[email protected]"). |
RTrim(str, chars string) | A sanitizer that trims characters (whitespace by default) from the right-side of the input. |
StripLow(str string, keepNewLines bool) | sanitizer that removes characters with a numerical value < 32 and 127 , mostly control characters. If keepNewLines is true, newline characters are preserved (\n and \r, hex 0xA and 0xD). |
ToBoolean(str string, strict bool) | A sanitizer that converts the input string to a boolean. Everything except for "0" , "false" and "" returns true . In strict mode only "1" and "true" return true . |
ToDate(str string) | A sanitizer that converts the input string to a pointer to time.Time , if the input is not of a time layout returns a nil pointer. e.g (Layout, ANSIC, UnixDate, RubyDate, RFC822, RFC822Z, RFC850, RFC1123, RFC1123Z, Kitchen, Stamp, StampMilli, StampMicro, StampNano, DateTime, DateOnly, TimeOnly) |
ToFloat(str string) | A sanitizer that converts the input string to a float64 and also returns an error if the input is not a float. |
ToInt(str string) | A sanitizer that converts the input string to an int and also returns an error if the input is not a int. (Beware of octals) |
Trim(str, chars string) | A sanitizer that trim characters (whitespace by default) from both sides of the input. |
Unescape(str string) | A sanitizer that replaces HTML encoded entities with <, >, &, ', ", `, \ and /. |
Whitelist(str, whitelistedChars string) | A sanitizer that removes characters that do not appear in the whitelist. The characters are used in a RegExp and will escaped for you. |
- bube054 - Attah Gbubemi David (author)
This project is licensed under the MIT. See the LICENSE file for details.