validatorgo

package module
v1.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 7, 2026 License: MIT Imports: 15 Imported by: 1

README

validatorgo

Go Reference Go Report Card Go Version

A comprehensive library of string validators and sanitizers for Go, inspired by the popular JavaScript library validator.js.


Table of Contents


Features

  • 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

Why validatorgo?

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.


Installation

go get -u github.com/bube054/validatorgo

Then import it in your code:

import (
    "fmt"
    "github.com/bube054/validatorgo"
)

Prefer a shorter alias?

import (
    "fmt"
    vgo "github.com/bube054/validatorgo"
)

Quick Start

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("[email protected]", nil)
fmt.Println(ok) // true

// Or customize only what you need
ok, err := vgo.IsEmail("[email protected]", &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.


Validators

Strings & Text
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.
Numbers & Booleans
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.
Dates & Times
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.

Network, Web & URIs
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").
Encoding, Hashes & JSON
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()).
Identifiers, Codes & Versioning
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.
Geographic & Locale
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.
Personal & Identity
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).
Finance & Crypto
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).
Colors & Data Structures
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.

Sanitizers

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.)

Error Handling

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.

Option fields

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)  // *float64

Example:

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.


Maintainers

Contributing

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.

License

This project is licensed under the MIT License. See LICENSE for details.

Documentation

Overview

A package of string validators.

Index

Constants

View Source
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.

View Source
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

View Source
var (
	IsTimeOptsHourFormat24 string = "hour24"
	IsTimeOptsHourFormat12 string = "hour12"

	IsTimeOptsModeDefault     string = "default"
	IsTimeOptsModeWithSeconds string = "withSeconds"
)
View Source
var AllCountryCodes = [...]string{} /* 237 elements not displayed */
View Source
var AllISO31661Alpha2 = [...]string{}/* 676 elements not displayed */
View Source
var AllISO31661Alpha3 = [...]string{}/* 243 elements not displayed */
View Source
var AllISO31661Numeric = [...]string{} /* 251 elements not displayed */
View Source
var AllISO4217Codes = [...]string{}/* 184 elements not displayed */
View Source
var AllISO6391Codes = [...]string{} /* 176 elements not displayed */
View Source
var AllLocales = [...]string{} /* 490 elements not displayed */
View Source
var (
	IsObjectOptsDefaultStrict = true
)

Functions

func Bool added in v1.0.0

func Bool(v bool) *bool

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

func Equals(str, comparison string) (bool, error)

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 Float64 added in v1.0.0

func Float64(v float64) *float64

Float64 returns a pointer to the given float64 value.

func Int added in v1.0.0

func Int(v int) *int

Int returns a pointer to the given int value.

func IsAbaRouting

func IsAbaRouting(str string) (bool, error)

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

func IsAscii(str string) (bool, error)

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

func IsBTCAddress(str string) (bool, error)

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 IsBase58

func IsBase58(str string) (bool, error)

A validator that checks if the string is base58 encoded.

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

func IsBic(str string) (bool, error)

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

func IsCountryCode(str string) (bool, error)

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

func IsDataURI(str string) (bool, error)

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

func IsDivisibleBy(str string, num int) (bool, error)

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

func IsEAN(str string) (bool, error)

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

func IsEthereumAddress(str string) (bool, error)

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

func IsFreightContainerID(str string) (bool, error)

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

func IsFullWidth(str string) (bool, error)

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

func IsHSL(str string) (bool, error)

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

func IsHalfWidth(str string) (bool, error)

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

func IsHash(str, algorithm string) (bool, error)

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

func IsHexColor(str string) (bool, error)

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

func IsHexadecimal(str string) (bool, error)

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

func IsIBAN(str, countryCode string) (bool, error)

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

func IsIP(str, version string) (bool, error)

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

func IsIPRange(str, version string) (bool, error)

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

func IsISBN(str, version string) (bool, error)

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

func IsISIN(str string) (bool, error)

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

func IsISO6346(str string) (bool, error)

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

func IsISO6391(str string) (bool, error)

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

func IsISO31661Alpha2(str string) (bool, error)

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

func IsISO31661Alpha3(str string) (bool, error)

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

func IsISO31661Numeric(str string) (bool, error)

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

func IsISRC(str string, allowHyphens bool) (bool, error)

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

func IsIdentityCard(str, locale string) (bool, error)

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

func IsIn(str string, values []string) (bool, error)

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

func IsInt(str string, opts *IsIntOpts) (bool, error)

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

func IsIso4217(str string) (bool, error)

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

func IsJSON(str string) (bool, error)

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

func IsJWT(str string) (bool, error)

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

func IsLicensePlate(str string, locale string) (bool, error)

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

func IsLocale(str string) (bool, error)

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

func IsLowerCase(str string) (bool, error)

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

func IsLuhnNumber(str string) (bool, error)

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

func IsMD5(str string) (bool, error)

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

func IsMagnetURI(str string) (bool, error)

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

func IsMimeType(str string) (bool, error)

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

func IsMongoID(str string) (bool, error)

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

func IsMultibyte(str string) (bool, error)

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

func IsOctal(str string) (bool, error)

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

func IsPassportNumber(str, countryCode string) (bool, error)

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

func IsPort(str string) (bool, error)

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

func IsPostalCode(str, locale string) (bool, error)

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

func IsRFC3339(str string) (bool, error)

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

func IsRgbColor(str string, opts *IsRgbOpts) (bool, error)

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

func IsSemVer(str string) (bool, error)

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

func IsSlug(str string) (bool, error)

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

func IsSurrogatePair(str string) (bool, error)

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

func IsTaxID(str, locale string) (bool, error)

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

func IsULID(str string) (bool, error)

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

func IsURL(str string, opts *IsURLOpts) (bool, error)

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

func IsUUID(str, version string) (bool, error)

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

func IsUpperCase(str string) (bool, error)

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

func IsVAT(str, countryCode string) (bool, error)

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

func IsVariableWidth(str string) (bool, error)

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

func IsWhitelisted(str, chars string) (bool, error)

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

func Matches(str string, re *regexp.Regexp) (bool, error)

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

func String added in v1.0.0

func String(v string) *string

String returns a pointer to the given string value.

func Uint added in v1.0.0

func Uint(v uint) *uint

Uint returns a pointer to the given uint value.

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

type IsAlphaOpts struct {
	Ignore *string // string to be ignored
	Locale *string // a locale
}

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

type IsArrayOpts struct {
	Min *uint // minimum array length
	Max *uint // maximum array length
}

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

type IsByteLengthOpts struct {
	Min *uint // minimum byte length
	Max *uint // maximum byte length
}

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

type IsDateOpts struct {
	Format     *string
	StrictMode *bool
}

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 IsFloatOpts struct {
	Min    *float64
	Max    *float64
	Gt     *float64
	Lt     *float64
	Locale *string
}

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 IsIntOpts

type IsIntOpts struct {
	Min *int // minimum integer
	Max *int // maximum integer

	Gt *int // integer to exceeds
	Lt *int // integer to subceed

	AllowLeadingZeroes *bool
}

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

type IsNumericOpts struct {
	NoSymbols *bool
	Locale    *string
}

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 IsTimeOpts struct {
	HourFormat *string // hour12 e.g 14:30 or hour24 e.g 02:30 PM
	Mode       *string // default e.g 13:30 or withSeconds e.g 13:30:20
}

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.

Directories

Path Synopsis
A package of string sanitizers.
A package of string sanitizers.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL