A comprehensive library of string validators and sanitizers for Go, inspired by the popular JavaScript library validator.js.
- Features
- Why validatorgo?
- Installation
- Quick Start
- Validators
- Sanitizers
- Error Handling
- Maintainers
- Contributing
- License
- 89+ validators covering everything from emails and URLs to IBANs and ISO codes
- 13 sanitizers for cleaning, normalizing, and converting input strings
- Structured errors — every validator returns
(bool, error)with machine-readable error codes - Locale-aware — many validators accept locale options for region-specific formats
- Pure Go, no heavy dependencies
- Comprehensive tests with ~87% coverage
- Drop-in mental model for anyone familiar with validator.js
Other popular Go libraries like go-playground/validator and asaskevich/govalidator primarily focus on validating structs, not standalone strings. They also lack the breadth of validators offered by validator.js.
validatorgo was originally built as a dependency for ginvalidator — a Go equivalent of the popular Node.js library express-validator. The existing Go ecosystem options were either too complex, not robust enough, or unsuitable for that use case, so this library fills the gap.
go get -u github.com/bube054/validatorgoThen import it in your code:
import (
"fmt"
"github.com/bube054/validatorgo"
)Prefer a shorter alias?
import (
"fmt"
vgo "github.com/bube054/validatorgo"
)Validate a MongoDB ObjectID:
package main
import (
"fmt"
vgo "github.com/bube054/validatorgo"
)
func main() {
id := "5f2a6c69e1d7a4e0077b4e6b"
ok, err := vgo.IsMongoID(id)
fmt.Println(ok) // true
fmt.Println(err) // <nil>
}Validate an email with options:
// Pass nil to use all defaults
ok, _ := vgo.IsEmail("user@example.com", nil)
fmt.Println(ok) // true
// Or customize only what you need
ok, err := vgo.IsEmail("user@example.com", &vgo.IsEmailOpts{
RequireTld: vgo.Bool(false), // override default (true)
DomainSpecificValidation: true,
})
fmt.Println(ok, err) // true <nil>Sanitize a string:
import "github.com/bube054/validatorgo/sanitizer"
clean := sanitizer.Whitelist("Hello123 World!", "a-zA-Z")
fmt.Println(clean) // "HelloWorld"For full API docs and parameter details, see the Go Reference.
| Validator | Description |
|---|---|
Contains(str, seed string, opts *ContainsOpt) |
Checks if a string contains a seed. ContainsOpt defaults to { IgnoreCase: false, MinOccurrences: 1 }. |
Equals(str, comparison string) |
Checks if the string matches the comparison. |
Matches(str string, re *regexp.Regexp) |
Checks if the string matches the given regex. |
IsEmpty(str string, opts *IsEmptyOpts) |
Checks if the string is zero-length. IsEmptyOpts defaults to { IgnoreWhitespace: false }. |
IsLowerCase(str string) |
Checks if the string is lowercase. |
IsUpperCase(str string) |
Checks if the string is uppercase. |
IsAscii(str string) |
Checks if the string contains ASCII characters only. |
IsAlpha(str string, opts *IsAlphaOpts) |
Checks if the string contains only letters (a-zA-Z). Supports Ignore and Locale options. Defaults to en-US. |
IsAlphanumeric(str string, opts *IsAlphanumericOpts) |
Checks if the string contains only letters and numbers (a-zA-Z0-9). Supports Ignore and Locale. |
IsByteLength(str string, opts *IsByteLengthOpts) |
Checks if the string's UTF-8 byte length falls within a range. Defaults to { Min: 0, Max: nil }. |
IsSlug(str string) |
Checks if the string is a valid slug. |
IsFullWidth(str string) |
Checks if the string contains any full-width characters. |
IsHalfWidth(str string) |
Checks if the string contains any half-width characters. |
IsMultibyte(str string) |
Checks if the string contains one or more multibyte characters. |
IsSurrogatePair(str string) |
Checks if the string contains any surrogate pair characters. |
IsVariableWidth(str string) |
Checks if the string contains a mixture of full and half-width characters. |
IsWhitelisted(str, chars string) |
Checks if the string consists only of characters in the given whitelist. |
| Validator | Description |
|---|---|
IsBoolean(str string, opts *IsBooleanOpts) |
Checks if the string is a boolean. |
IsInt(str string, opts *IsIntOpts) |
Checks if the string is an integer. Supports Min, Max, Gt, Lt, and AllowLeadingZeroes. |
IsFloat(str string, opts *IsFloatOpts) |
Checks if the string is a float. Supports Min/Max (≤ ≥), Gt/Lt (strict), and Locale. |
IsDecimal(str string, opts *IsDecimalOpts) |
Checks if the string represents a decimal number (0.1, .3, 1.1, etc.). Supports ForceDecimal, DecimalDigits, and Locale. |
IsDivisibleBy(str string, num int) |
Checks if the string is an integer divisible by num. |
IsNumeric(str string, opts *IsNumericOpts) |
Checks if the string is numeric. NoSymbols rejects +, -, .. Supports Locale. |
IsPort(str string) |
Checks if the string is a valid port number (0–65535). |
IsHexadecimal(str string) |
Checks if the string is a hexadecimal number. |
IsOctal(str string) |
Checks if the string is a valid octal number. |
IsLuhnNumber(str string) |
Checks if the string passes the Luhn algorithm. |
| Validator | Description |
|---|---|
IsDate(str string, opts *IsDateOpts) |
Checks if the string is a valid date (e.g. 2002-07-15). Supports Format and StrictMode. |
IsAfter(str string, opts *IsAfterOpts) |
Checks if the string is a date after the given ComparisonDate (defaults to now). |
IsBefore(str string, opts *IsBeforeOpts) |
Checks if the string is a date before the given ComparisonDate (defaults to now). |
IsTime(str string, opts *IsTimeOpts) |
Checks if the string is a valid time (e.g. 23:01:59). Supports HourFormat (hour12/hour24) and Mode (default/withSeconds). |
IsRFC3339(str string) |
Checks if the string is a valid RFC 3339 date. |
IsISO8601(str string, opts *IsISO8601Opts) |
Checks if the string is a valid ISO 8601 date. Supports Strict and StrictSeparator. |
Supported time layouts:
Layout,ANSIC,UnixDate,RubyDate,RFC822(Z),RFC850,RFC1123(Z),Kitchen,Stamp/StampMilli/StampMicro/StampNano,DateTime,DateOnly,TimeOnly, plus custom:StandardDateLayout,SlashDateLayout,DateTimeLayout,ISO8601Layout,ISO8601ZuluLayout,ISO8601WithMillisecondsLayout.
| Validator | Description |
|---|---|
IsEmail(str string, opts *IsEmailOpts) |
Checks if the string is an email. Supports AllowDisplayName, RequireDisplayName, AllowUTF8LocalPart, RequireTld, AllowIpDomain, DomainSpecificValidation, BlacklistedChars, HostBlacklist, HostWhitelist, IgnoreMaxLength. |
IsURL(str string, opts *IsURLOpts) |
Checks if the string is a URL. Highly configurable — see godoc for full options including Protocols, RequireTld, RequireProtocol, RequireHost, RequirePort, HostWhitelist/HostBlacklist, AllowFragments, MaxAllowedLength, etc. |
IsIP(str, version string) |
Checks if the string is an IP address. version is "4", "6", or empty for both. |
IsIPRange(str, version string) |
Checks if the string is an IP range. version is "4", "6", or empty for both. |
IsFQDN(str string, opts *IsFQDNOpts) |
Checks if the string is a fully qualified domain name. Supports RequireTld, AllowUnderscores, AllowTrailingDot, AllowNumericTld, AllowWildcard, IgnoreMaxLength. |
IsMagnetURI(str string) |
Checks if the string is a Magnet URI. |
IsMailtoURI(str string, opts *IsMailToURIOpts) |
Checks if the string is a Mailto URI. Embeds IsEmailOpts for inner email validation. |
IsDataURI(str string) |
Checks if the string is in data: URI format. |
IsMimeType(str string) |
Checks if the string matches a valid MIME type format. |
IsMacAddress(str string, opts *IsMacAddressOpts) |
Checks if the string is a MAC address. Supports NoSeparators and Type ("48" or "64"). |
| Validator | Description |
|---|---|
IsBase32(str string, opts *IsBase32Opts) |
Checks if the string is Base32-encoded. Crockford enables Crockford's variant. |
IsBase58(str string) |
Checks if the string is Base58-encoded. |
IsBase64(str string, opts *IsBase64Opts) |
Checks if the string is Base64-encoded. UrlSafe enables URL-safe Base64. |
IsHash(str, algorithm string) |
Checks if the string is a hash of the given algorithm: crc32, crc32b, md4, md5, ripemd128, ripemd160, sha1, sha256, sha384, sha512, tiger128, tiger160, tiger192. |
IsMD5(str string) |
Convenience for IsHash(str, "md5"). |
IsJSON(str string) |
Checks if the string is valid JSON (uses json.Valid()). |
| Validator | Description |
|---|---|
IsUUID(str, version string) |
Checks if the string is an RFC 9562 UUID. version is "1"–"5", or empty for any. |
IsMongoID(str string) |
Checks if the string is a valid MongoDB ObjectId (hex-encoded). |
IsULID(str string) |
Checks if the string is a ULID. |
IsSemVer(str string) |
Checks if the string follows Semantic Versioning. |
IsISIN(str string) |
Checks if the string is an ISIN (stock/security identifier). |
IsISBN(str, version string) |
Checks if the string is an ISBN. version is "10", "13", or empty for both. |
IsISSN(str string, opts *IsISSNOpts) |
Checks if the string is an ISSN. Supports CaseSensitive and RequireHyphen. |
IsISRC(str string, allowHyphens bool) |
Checks if the string is an ISRC. |
IsEAN(str string) |
Checks if the string is a valid EAN (European Article Number). |
IsIMEI(str string, opts *IsIMEIOpts) |
Checks if the string is a valid IMEI. AllowHyphens switches between formats. |
IsFreightContainerID(str string) |
Alias for IsISO6346. |
IsISO6346(str string) |
Checks if the string is a valid ISO 6346 shipping container ID. |
| Validator | Description |
|---|---|
IsLocale(str string) |
Checks if the string is a valid locale identifier. |
IsISO6391(str string) |
Checks if the string is a valid ISO 639-1 language code. |
IsISO31661Alpha2(str string) |
Checks if the string is a valid ISO 3166-1 alpha-2 country code. |
IsISO31661Alpha3(str string) |
Checks if the string is a valid ISO 3166-1 alpha-3 country code. |
IsISO31661Numeric(str string) |
Checks if the string is a valid ISO 3166-1 numeric country code. |
IsPostalCode(str, locale string) |
Checks if the string is a valid postal code. Pass "any" or empty to match any supported locale. |
IsLatLong(str string, opts *IsLatLongOpts) |
Checks if the string is a valid lat,long pair. CheckDMS validates degrees-minutes-seconds format. |
IsLicensePlate(str, locale string) |
Checks if the string matches a country's license plate format. Locales: cs-CZ, de-DE, de-LI, en-IN, en-SG, en-PK, es-AR, hu-HU, pt-BR, pt-PT, sq-AL, sv-SE, or any. |
| Validator | Description |
|---|---|
IsMobilePhone(str string, locales []string, opts *IsMobilePhoneOpts) |
Checks if the string is a mobile phone number. Pass a slice of locales (e.g. []string{"sk-SK", "sr-RS"}) or nil for any. StrictMode requires a leading +. Supports 150+ locales. |
IsIdentityCard(str, locale string) |
Checks if the string is a valid identity card code. Locales include 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. |
IsPassportNumber(str, countryCode string) |
Checks if the string is a valid passport number for the given country. |
IsTaxID(str, locale string) |
Checks if the string is a valid Tax Identification Number. Defaults to en-US; any matches any supported locale. |
IsVAT(str, countryCode string) |
Checks if the string is a valid VAT number for the given ISO 3166-1 alpha-2 country code (or any). |
IsStrongPassword(str string, opts *IsStrongPasswordOpts) |
Checks password strength against configurable rules (min length, casing, numbers, symbols, scoring). |
| Validator | Description |
|---|---|
IsCreditCard(str string, opts *IsCreditCardOpts) |
Checks if the string is a credit card number. Provider can restrict to: amex, bcglobal, carteblanche, dinersclub, discover, instapayment, jcb, koreanlocal, laser, maestro, mastercard, solo, switch, unionpay, visa, visamastercard. |
IsCurrency(str string, opts *IsCurrencyOpts) |
Checks if the string is a valid currency amount. Highly configurable (symbol, separators, negatives, decimals — see godoc). |
IsBic(str string) |
Checks if the string is a BIC (Bank Identifier Code) / SWIFT code. |
IsIBAN(str, countryCode string) |
Checks if the string is a valid IBAN. Supports 70+ country codes (no checksum). |
IsAbaRouting(str string) |
Checks if the string is a valid ABA routing number (US bank). |
IsIso4217(str string) |
Checks if the string is a valid ISO 4217 currency code. |
IsBTCAddress(str string) |
Checks if the string is a valid Bitcoin address. |
IsEthereumAddress(str string) |
Checks if the string is an Ethereum address (no checksum validation). |
| Validator | Description |
|---|---|
IsHexColor(str string) |
Checks if the string is a hex color. |
IsHSL(str string) |
Checks if the string is an HSL color (CSS Colors Level 4). |
IsRgbColor(str string, opts *IsRgbOpts) |
Checks if the string is an RGB or RGBA color. Supports IncludePercentValues and AllowSpaces. |
IsArray(str string, opts *IsArrayOpts) |
Checks if the value is an array. Min/Max constrain the length. |
IsObject(str string, opts *IsObjectOpts) |
Checks if the value is a JSON object (e.g. {}, {"foo":"bar"}). With Strict: false, arrays and null also pass. |
IsIn(str string, values []string) |
Checks if the string appears in a list of allowed values. |
import "github.com/bube054/validatorgo/sanitizer"
clean := sanitizer.Whitelist("Hello123 World!", "a-zA-Z")
fmt.Println(clean) // "HelloWorld"| Sanitizer | Description |
|---|---|
Blacklist(str, blacklistedChars string) |
Removes characters that match the blacklist (auto-escaped for regex). |
Whitelist(str, whitelistedChars string) |
Removes characters not in the whitelist (auto-escaped for regex). |
Escape(str string) |
Replaces <, >, &, ', and " with HTML entities. |
Unescape(str string) |
Reverses Escape — replaces HTML entities with their characters. |
LTrim(str, chars string) |
Trims characters (whitespace by default) from the left side. |
RTrim(str, chars string) |
Trims characters (whitespace by default) from the right side. |
Trim(str, chars string) |
Trims characters (whitespace by default) from both sides. |
StripLow(str string, keepNewLines bool) |
Removes characters with code < 32 and code 127 (mostly control chars). Preserves newlines if keepNewLines is true. |
NormalizeEmail(email string, opts *NormalizeEmailOpts) |
Canonicalizes an email address. Provider-aware (Gmail, Outlook, Yahoo, iCloud) — handles dots, sub-addresses, and casing per provider rules. |
ToBoolean(str string, strict bool) |
Converts the string to a bool. Everything except "0", "false", and "" returns true. In strict mode, only "1" and "true" return true. |
ToDate(str string) |
Converts the string to *time.Time, or nil if unparseable. |
ToFloat(str string) |
Converts the string to float64, returning an error on failure. |
ToInt(str string) |
Converts the string to int, returning an error on failure. (Beware of octals.) |
All validators return (bool, error). On success, err is nil. On failure, err is a *ValidationError with machine-readable context:
ok, err := validatorgo.IsEmail("bad-email", nil)
if err != nil {
var ve *validatorgo.ValidationError
if errors.As(err, &ve) {
fmt.Println(ve.Validator) // "IsEmail"
fmt.Println(ve.Code) // "INVALID_FORMAT"
fmt.Println(ve.Message) // "invalid email format"
}
}Error codes: INVALID_FORMAT, TOO_SHORT, TOO_LONG, MISSING_TLD, BLACKLISTED_HOST, NOT_WHITELISTED_HOST, BLACKLISTED_CHAR, INVALID_LOCALE, OUT_OF_RANGE, INVALID_CHECKSUM, INVALID_LENGTH, MISSING_REQUIRED, INVALID_DOMAIN, UNSUPPORTED_VERSION, INVALID_VALUE, NOT_FOUND.
All option struct fields use pointer types. Pass nil for the opts parameter to use defaults, or set only the fields you care about using the exported helpers:
validatorgo.Bool(true) // *bool
validatorgo.String("foo") // *string
validatorgo.Int(42) // *int
validatorgo.Uint(10) // *uint
validatorgo.Float64(3.14) // *float64Example:
ok, _ := validatorgo.IsFQDN("example.com", &validatorgo.IsFQDNOpts{
RequireTld: validatorgo.Bool(false), // override default (true)
AllowTrailingDot: validatorgo.Bool(true),
})Any field left as nil gets its default value automatically.
- Attah Gbubemi David (@bube054) — author
Contributions are welcome! Please read CONTRIBUTING.md and the Code of Conduct before opening a PR.
A few quick guidelines:
- Match the style and structure of existing validators.
- Add tests for any new functionality (we aim for high coverage).
- Update this README's table when adding a new validator or sanitizer.
This project is licensed under the MIT License. See LICENSE for details.