Documentation
¶
Overview ¶
Package validate provides standalone validation checks returning error. Use package it for constraints with translated violations and property paths.
Index ¶
- Constants
- Variables
- func AllowNonCanonicalUUIDFormats() func(o *UUIDOptions)
- func AllowUUIDVersions(versions ...byte) func(o *UUIDOptions)
- func BIC(value string, options ...func(*BICOptions)) error
- func BICCaseInsensitive() func(*BICOptions)
- func BICWithIBAN(iban string) func(*BICOptions)
- func CIDR(value string, options ...func(*CIDROptions)) error
- func CIDRNetmaskRange(netmaskMin, netmaskMax int) func(*CIDROptions)
- func CIDRVersion(version string) func(*CIDROptions)
- func CIDRViolationNetmaskBounds(value string, options ...func(*CIDROptions)) (lo, hi int)
- func CSSColor(value string, formats ...CSSColorFormat) error
- func CardScheme(value string, schemes ...CardSchemeName) error
- func ContentType(data []byte, types []string, options ...func(*ContentTypeOptions)) error
- func Country(value string) error
- func Currency(value string) error
- func DenyNilUUID() func(o *UUIDOptions)
- func DenyPrivateIP() func(ip net.IP) error
- func EAN8(value string) error
- func EAN13(value string) error
- func FileExtension(name string, extensions ...string) error
- func FileName(name string, options ...func(*FileNameOptions)) error
- func IBAN(value string) error
- func IP(value string, restrictions ...func(ip net.IP) error) error
- func IPv4(value string, restrictions ...func(ip net.IP) error) error
- func IPv6(value string, restrictions ...func(ip net.IP) error) error
- func ISBN(value string, options ...func(*ISBNOptions)) error
- func ISBNOnly10() func(*ISBNOptions)
- func ISBNOnly13() func(*ISBNOptions)
- func ISIN(value string) error
- func ISSN(value string) error
- func LUHN(value string) error
- func Language(value string) error
- func Locale(value string) error
- func MIMEType(value string, types ...string) error
- func MacAddress(value string, options ...func(*MacAddressOptions)) error
- func NoSuspiciousCharacters(value string, options ...NoSuspiciousCharactersOption) error
- func PasswordStrength(password string, options ...func(*PasswordStrengthOptions)) error
- func RestrictURLHostByPattern(pattern *regexp.Regexp) func(u *url.URL) error
- func RestrictURLHosts(hosts ...string) func(u *url.URL) error
- func RestrictURLSchemas(schemas ...string) func(u *url.URL) error
- func Timezone(value string, options ...func(*TimezoneOptions)) error
- func ULID(value string) error
- func UPCA(value string) error
- func UPCE(value string) error
- func URL(value string, restrictions ...func(u *url.URL) error) error
- func UTF8(value string) error
- func UUID(value string, options ...func(o *UUIDOptions)) error
- func Week(value string, options ...func(*WeekOptions)) error
- func WithContentTypeDetector(detector ContentTypeDetector) func(*ContentTypeOptions)
- func WithMacAddressType(t MacAddressType) func(*MacAddressOptions)
- func WithMaxWeek(value string) func(*WeekOptions)
- func WithMinPasswordStrength(score PasswordStrengthScore) func(*PasswordStrengthOptions)
- func WithMinWeek(value string) func(*WeekOptions)
- func WithPasswordStrengthEstimator(estimator PasswordStrengthEstimator) func(*PasswordStrengthOptions)
- func WithTimezoneZone(zone TimezoneZone) func(*TimezoneOptions)
- func WithWindowsFileNameRestrictions() func(*FileNameOptions)
- type BICOptions
- type CIDROptions
- type CSSColorFormat
- type CardSchemeName
- type ContentTypeDetector
- type ContentTypeOptions
- type FileNameOptions
- type ISBNOptions
- type ISBNType
- type MacAddressOptions
- type MacAddressType
- type NoSuspiciousCharactersOption
- type NoSuspiciousCharactersOptions
- type PasswordStrengthEstimator
- type PasswordStrengthOptions
- type PasswordStrengthScore
- type SuspiciousRestriction
- type TimezoneOptions
- type TimezoneZone
- type UUIDOptions
- type WeekOptions
Examples ¶
Constants ¶
const ( CheckSuspiciousInvisible uint = 32 // CHECK_INVISIBLE CheckSuspiciousMixedNumbers uint = 128 // CHECK_MIXED_NUMBERS CheckSuspiciousHiddenOverlay uint = 256 // CHECK_HIDDEN_OVERLAY )
Suspicious check flags mirror Symfony NoSuspiciousCharacters bit values for API familiarity. See https://symfony.com/doc/current/reference/constraints/NoSuspiciousCharacters.html
const DefaultSuspiciousChecks = CheckSuspiciousInvisible | CheckSuspiciousMixedNumbers | CheckSuspiciousHiddenOverlay
DefaultSuspiciousChecks runs all standard spoofing checks (invisible, mixed digit scripts, hidden overlay).
Variables ¶
var ( ErrOnlyZeros = errors.New("contains only zeros") ErrInvalidChecksum = errors.New("invalid checksum") ErrUnexpectedLength = errors.New("unexpected length") ErrContainsNonDigit = errors.New("contains non-digit") )
var ( // ErrInvalidCardScheme indicates a number that does not match any selected scheme. ErrInvalidCardScheme = errors.New("invalid card scheme") // ErrInvalidCardSchemes indicates an empty selection or an unknown scheme name. ErrInvalidCardSchemes = errors.New("invalid card schemes") )
var ( // ErrInvalidCIDR is returned when the value is not valid CIDR notation (missing slash, // non-digit prefix, invalid IP, or IP version does not match the configured version). ErrInvalidCIDR = errors.New("invalid CIDR") // ErrCIDRNetmaskOutOfRange is returned when the prefix length is outside the allowed // [netmaskMin, netmaskMax] range (after capping max to 32 for IPv4 when needed), // matching Symfony\Component\Validator\Constraints\CidrValidator. ErrCIDRNetmaskOutOfRange = errors.New("CIDR netmask out of range") )
var ( // ErrInvalidCSSColor indicates an unsupported or malformed color. ErrInvalidCSSColor = errors.New("invalid CSS color") // ErrInvalidCSSColorFormats indicates an unknown format in the selection. ErrInvalidCSSColorFormats = errors.New("invalid CSS color formats") )
var ( ErrInvalid = errors.New("invalid") ErrProhibited = errors.New("prohibited") )
var ( // ErrInvalidFileName indicates an invalid file name. ErrInvalidFileName = errors.New("invalid file name") // ErrInvalidFileExtension indicates a disallowed extension or invalid name. ErrInvalidFileExtension = errors.New("invalid file extension") // ErrInvalidMIMEType indicates malformed or disallowed MIME metadata. ErrInvalidMIMEType = errors.New("invalid MIME type") // ErrInvalidContentType indicates disallowed detected content. ErrInvalidContentType = errors.New("invalid content type") // ErrInvalidFileExtensions indicates an invalid extension allowlist. ErrInvalidFileExtensions = errors.New("invalid file extensions") // ErrInvalidMIMETypes indicates an invalid MIME allowlist. ErrInvalidMIMETypes = errors.New("invalid MIME types") // ErrInvalidDetectedContentType indicates a detector contract violation. ErrInvalidDetectedContentType = errors.New("invalid detected content type") )
var ( ErrTooShort = errors.New("too short") ErrTooLong = errors.New("too long") ErrTooLarge = errors.New("too large") ErrInvalidCharacters = errors.New("invalid characters") ErrInvalidHyphenPlacement = errors.New("invalid hyphen placement") ErrInvalidVersion = errors.New("invalid version") ErrIsNil = errors.New("is nil") )
var ( // ErrInvalidCountry indicates an invalid two-letter country or territory code. ErrInvalidCountry = errors.New("invalid country") // ErrInvalidLanguage indicates an invalid standalone language code. ErrInvalidLanguage = errors.New("invalid language") // ErrInvalidLocale indicates an invalid locale identifier. ErrInvalidLocale = errors.New("invalid locale") )
var ( ErrISBNInvalidCharacters = errors.New("ISBN invalid characters") ErrISBNTooShort = errors.New("ISBN too short") ErrISBNTooLong = errors.New("ISBN too long") ErrISBNChecksumFailed = errors.New("ISBN checksum failed") ErrISBNTypeNotRecognized = errors.New("ISBN type not recognized") )
ISBN validation errors, aligned with Symfony\Component\Validator\Constraints\Isbn codes.
var ( // ErrPasswordTooWeak indicates a score below the configured minimum. ErrPasswordTooWeak = errors.New("password strength too low") // ErrInvalidPasswordStrengthMinimum indicates a minimum outside 1–4. ErrInvalidPasswordStrengthMinimum = errors.New("invalid password strength minimum") // ErrInvalidPasswordStrengthScore indicates an estimator result outside 0–4. ErrInvalidPasswordStrengthScore = errors.New("invalid password strength score") )
var ( // ErrSuspiciousInvisible is returned when invisible or format-control characters are present. ErrSuspiciousInvisible = errors.New("suspicious invisible characters") // ErrSuspiciousMixedNumbers is returned when decimal digits from more than one numbering system are mixed. ErrSuspiciousMixedNumbers = errors.New("suspicious mixed digit scripts") // ErrSuspiciousHiddenOverlay is returned for combining sequences that can hide in the preceding glyph (e.g. Latin i + U+0307). ErrSuspiciousHiddenOverlay = errors.New("suspicious hidden overlay") // ErrSuspiciousRestriction is returned when a rune’s script is not allowed for the configured locales or single-script rule. ErrSuspiciousRestriction = errors.New("suspicious script restriction") )
var ( ErrRestrictedSchema = errors.New("restricted schema") ErrRestrictedHost = errors.New("restricted host") )
var ( // ErrInvalidWeekFormat indicates a value outside the YYYY-Www format (weeks 01–53). ErrInvalidWeekFormat = errors.New("invalid week format") // ErrInvalidWeekNumber indicates week 53 in an ISO year with only 52 weeks. ErrInvalidWeekNumber = errors.New("invalid week number") // ErrWeekTooEarly indicates a week before the inclusive minimum. ErrWeekTooEarly = errors.New("week too early") // ErrWeekTooLate indicates a week after the inclusive maximum. ErrWeekTooLate = errors.New("week too late") // ErrInvalidWeekBounds indicates malformed, nonexistent, or reversed bounds. ErrInvalidWeekBounds = errors.New("invalid week bounds") )
var ErrBICIBANCountryMismatch = errors.New("BIC country does not match IBAN")
ErrBICIBANCountryMismatch is returned by BIC when an associated IBAN is set and its country code does not match the BIC's country/territory code (using the same territory mapping as Symfony BicValidator).
var ErrInvalidBIC = errors.New("invalid BIC")
ErrInvalidBIC is returned by BIC when the value is not a valid Business Identifier Code (BIC / SWIFT). Behavior is aligned with Symfony\Component\Validator\Constraints\Bic and BicValidator (country check via ISO 3166-1 alpha-2 regions known to golang.org/x/text/language plus Symfony's BIC-to-IBAN territory map).
var ErrInvalidCurrency = errors.New("invalid currency")
ErrInvalidCurrency is returned by Currency when the value is not a valid ISO 4217 currency code.
var ErrInvalidIBAN = errors.New("invalid IBAN")
ErrInvalidIBAN is returned by IBAN when the value is not a valid International Bank Account Number. Behavior is aligned with Symfony\Component\Validator\Constraints\Iban and IbanValidator.
var ErrInvalidMAC = errors.New("invalid MAC address")
ErrInvalidMAC is returned when the value is not a valid 48-bit MAC address for the configured checks, or when an unknown Symfony type name was set via WithMacAddressType.
var ErrInvalidTimezone = errors.New("invalid timezone")
ErrInvalidTimezone is returned by Timezone when the value is not a valid IANA timezone identifier.
var ErrInvalidUTF8 = errors.New("invalid UTF-8")
ErrInvalidUTF8 indicates a malformed UTF-8 byte sequence.
Functions ¶
func AllowNonCanonicalUUIDFormats ¶ added in v0.17.0
func AllowNonCanonicalUUIDFormats() func(o *UUIDOptions)
AllowNonCanonicalUUIDFormats used to enable parsing UUID value from non-canonical formats.
Following formats are supported:
- "6ba7b810-9dad-11d1-80b4-00c04fd430c8",
- "{6ba7b810-9dad-11d1-80b4-00c04fd430c8}",
- "urn:uuid:6ba7b810-9dad-11d1-80b4-00c04fd430c8"
- "6ba7b8109dad11d180b400c04fd430c8"
- "{6ba7b8109dad11d180b400c04fd430c8}",
- "urn:uuid:6ba7b8109dad11d180b400c04fd430c8".
func AllowUUIDVersions ¶ added in v0.17.0
func AllowUUIDVersions(versions ...byte) func(o *UUIDOptions)
AllowUUIDVersions used to set valid versions of the UUID value. If the versions are empty, the UUID will be checked for compliance with the default registered versions: 1, 2, 3, 4, 5, 6 or 7.
func BIC ¶ added in v0.20.0
func BIC(value string, options ...func(*BICOptions)) error
BIC validates whether the value is a valid Business Identifier Code (BIC / SWIFT), aligned with Symfony\Component\Validator\Constraints\Bic and BicValidator.
Spaces (U+0020) are stripped before validation, matching Symfony str_replace(' ', ”, $value).
Empty string is considered valid (use [NotBlank] or similar to reject empty values).
Possible errors:
- ErrInvalidBIC when length, characters, country/territory, or strict-case rules fail;
- ErrBICIBANCountryMismatch when BICWithIBAN is set with a non-empty IBAN whose first two letters (after IBAN canonicalization) form an alpha country code that does not match the BIC territory.
See https://en.wikipedia.org/wiki/ISO_9362.
Example ¶
package main
import (
"fmt"
"github.com/muonsoft/validation/validate"
)
func main() {
fmt.Println(validate.BIC("DEUTDEFF"))
fmt.Println(validate.BIC("DEUTDEF"))
fmt.Println(validate.BIC("deutdeff", validate.BICCaseInsensitive()))
}
Output: <nil> invalid BIC <nil>
func BICCaseInsensitive ¶ added in v0.20.0
func BICCaseInsensitive() func(*BICOptions)
BICCaseInsensitive enables case-insensitive validation (Symfony Bic::VALIDATION_MODE_CASE_INSENSITIVE): lowercase letters are allowed, and the BIC country/territory code is matched case-insensitively. The default is strict mode (uppercase ASCII only).
func BICWithIBAN ¶ added in v0.20.0
func BICWithIBAN(iban string) func(*BICOptions)
BICWithIBAN sets an IBAN value to assert that its country code matches the BIC's territory/country (same rules as Symfony Bic constraint "iban" option).
func CIDR ¶ added in v0.20.0
func CIDR(value string, options ...func(*CIDROptions)) error
CIDR validates that value is a valid CIDR notation (IP/prefix), aligned with Symfony\Component\Validator\Constraints\Cidr and CidrValidator.
Empty string is valid (use [NotBlank] or similar to reject empty values).
Possible errors:
- ErrInvalidCIDR for malformed notation, invalid IP, or version mismatch;
- ErrCIDRNetmaskOutOfRange when the prefix is outside the configured netmask range (the effective maximum is capped at 32 for IPv4 and 128 for IPv6).
Example ¶
package main
import (
"fmt"
"github.com/muonsoft/validation/validate"
)
func main() {
fmt.Println(validate.CIDR("192.168.0.0/24"))
fmt.Println(validate.CIDR("10.0.0.0/33"))
fmt.Println(validate.CIDR("2001:db8::/32", validate.CIDRVersion("4")))
}
Output: <nil> CIDR netmask out of range invalid CIDR
func CIDRNetmaskRange ¶ added in v0.20.0
func CIDRNetmaskRange(netmaskMin, netmaskMax int) func(*CIDROptions)
CIDRNetmaskRange sets the inclusive allowed range for the CIDR prefix length. Defaults are 0–128 for "all", 0–32 for IPv4-only, 0–128 for IPv6-only (Symfony Cidr defaults). The maximum is capped at the address size: 32 for IPv4 and 128 for IPv6.
func CIDRVersion ¶ added in v0.20.0
func CIDRVersion(version string) func(*CIDROptions)
CIDRVersion sets which IP versions are accepted: "4" (IPv4 only), "6" (IPv6 only), or "all". The default is "all". Invalid values are ignored (default remains).
func CIDRViolationNetmaskBounds ¶ added in v0.20.0
func CIDRViolationNetmaskBounds(value string, options ...func(*CIDROptions)) (lo, hi int)
CIDRViolationNetmaskBounds returns the configured inclusive lower bound and the effective upper bound for the prefix length in Symfony-style out-of-range messages (caps the upper bound at 32 for IPv4 and 128 for IPv6).
func CSSColor ¶ added in v0.20.0
func CSSColor(value string, formats ...CSSColorFormat) error
CSSColor validates a color using Symfony 8.0's supported syntaxes. No formats selects all formats; multiple formats use OR semantics. Names and function names are ASCII case-insensitive. Input is not trimmed. RGB/HSL functions use the legacy comma-separated syntax and strict ranges; modern CSS color functions, percentages in RGB, and CSS-wide keywords are unsupported. Empty values are valid; use [NotBlank] to require a value. Unknown formats return ErrInvalidCSSColorFormats, even for empty input. Unsupported values return ErrInvalidCSSColor.
Example ¶
package main
import (
"fmt"
"github.com/muonsoft/validation/validate"
)
func main() {
fmt.Println(validate.CSSColor("#AbCd"))
fmt.Println(validate.CSSColor("red", validate.CSSColorRGB))
}
Output: <nil> invalid CSS color
func CardScheme ¶ added in v0.20.0
func CardScheme(value string, schemes ...CardSchemeName) error
CardScheme checks a card number against one or more explicitly selected schemes. Only ASCII digits are accepted; spaces, hyphens, and other formatting are not removed. This checks prefixes and lengths, not the LUHN checksum or whether a card exists or can be charged. See LUHN for a separate checksum check. Empty values are valid; use [NotBlank] to require a value. Missing or unknown schemes return ErrInvalidCardSchemes, even for empty input. Nonmatching numbers return ErrInvalidCardScheme.
Example ¶
package main
import (
"fmt"
"github.com/muonsoft/validation/validate"
)
func main() {
fmt.Println(validate.CardScheme("4111111111111111", validate.CardSchemeVisa))
fmt.Println(validate.CardScheme("4111111111111111", validate.CardSchemeMastercard))
}
Output: <nil> invalid card scheme
func ContentType ¶ added in v0.20.0
func ContentType(data []byte, types []string, options ...func(*ContentTypeOptions)) error
ContentType checks detected content against a nonempty allowlist of concrete MIME types without parameters. Nil and empty data are skipped. The default detector inspects at most 512 bytes; unknown content is application/octet-stream and only passes when explicitly allowed. No I/O or complete-file parsing occurs. Invalid lists return ErrInvalidMIMETypes; invalid detector results return ErrInvalidDetectedContentType; mismatches return ErrInvalidContentType.
Example ¶
package main
import (
"fmt"
"github.com/muonsoft/validation/validate"
)
func main() {
fmt.Println(validate.ContentType([]byte("hello"), []string{"text/plain"}))
fmt.Println(validate.ContentType([]byte{0, 1, 2}, []string{"text/plain"}))
}
Output: <nil> invalid content type
func Country ¶ added in v0.20.0
Country validates a two-letter country or territory code using language.ParseRegion and language.Region.IsCountry. It returns nil for an empty or valid value, otherwise ErrInvalidCountry. Case is ignored; whitespace, three-letter codes, numeric regions, and region groups are rejected.
Use it for country fields in addresses or APIs. The data comes from x/text, including CLDR additions and recognized historical codes, rather than a strict list of currently assigned ISO 3166-1 codes. For example, XK, UK, SU, and the special code UN pass; EU and ZZ do not. Acceptance does not imply delivery or service availability. Values are not modified; recognized codes may change with the x/text version.
Example ¶
package main
import (
"fmt"
"github.com/muonsoft/validation/validate"
)
func main() {
fmt.Println(validate.Country("de"))
fmt.Println(validate.Country("EU"))
}
Output: <nil> invalid country
func Currency ¶ added in v0.20.0
Currency validates whether the value is a recognized ISO 4217 alphabetic currency code (three letters). Letter case is normalized the same way as golang.org/x/text/currency.ParseISO (all upper or all lower).
Empty string is considered valid (use [NotBlank] or similar to reject empty values).
Possible errors:
- ErrInvalidCurrency when the string is not exactly three letters, is malformed, or is not a known code.
See https://www.iso.org/iso-4217-currency-codes.html and golang.org/x/text/currency.ParseISO.
Example ¶
package main
import (
"fmt"
"github.com/muonsoft/validation/validate"
)
func main() {
fmt.Println(validate.Currency("EUR"))
fmt.Println(validate.Currency("ZZZ"))
fmt.Println(validate.Currency("EU"))
}
Output: <nil> invalid currency invalid currency
func DenyNilUUID ¶ added in v0.17.0
func DenyNilUUID() func(o *UUIDOptions)
DenyNilUUID used to treat nil UUID ("00000000-0000-0000-0000-000000000000") value as invalid.
func DenyPrivateIP ¶
DenyPrivateIP denies using of private IPs according to RFC 1918 (IPv4 addresses) and RFC 4193 (IPv6 addresses).
func EAN8 ¶ added in v0.8.0
EAN8 checks that string contains valid EAN-8 code.
If the value is not valid then one of the errors will be returned:
- ErrOnlyZeros if code contains only zeros;
- ErrInvalidChecksum if check digit is not valid;
- ErrUnexpectedLength if value length has an unexpected size;
- ErrContainsNonDigit if string contains non-digit value.
See https://en.wikipedia.org/wiki/EAN-8.
Example ¶
package main
import (
"fmt"
"github.com/muonsoft/validation/validate"
)
func main() {
fmt.Println(validate.EAN8("42345671"))
fmt.Println(validate.EAN8("00000000"))
fmt.Println(validate.EAN8("42345670"))
fmt.Println(validate.EAN8("423456712"))
fmt.Println(validate.EAN8("A4234671"))
}
Output: <nil> contains only zeros invalid checksum unexpected length contains non-digit: 'A'
func EAN13 ¶ added in v0.8.0
EAN13 checks that string contains valid EAN-13 code.
If the value is not valid then one of the errors will be returned:
- ErrOnlyZeros if code contains only zeros;
- ErrInvalidChecksum if check digit is not valid;
- ErrUnexpectedLength if value length has an unexpected size;
- ErrContainsNonDigit if string contains non-digit value.
See https://en.wikipedia.org/wiki/International_Article_Number.
Example ¶
package main
import (
"fmt"
"github.com/muonsoft/validation/validate"
)
func main() {
fmt.Println(validate.EAN13("4719512002889"))
fmt.Println(validate.EAN13("0000000000000"))
fmt.Println(validate.EAN13("2266111566"))
fmt.Println(validate.EAN13("A782868890061"))
fmt.Println(validate.EAN13("4006381333932"))
}
Output: <nil> contains only zeros unexpected length contains non-digit: 'A' invalid checksum
func FileExtension ¶ added in v0.20.0
FileExtension checks an ASCII case-insensitive extension allowlist, accepting entries with or without a leading dot and compound extensions such as tar.gz. Entries contain nonempty dot-separated ASCII letters, digits, _, + or -. A matching suffix needs a nonempty stem. Paths are rejected; no basename is extracted. Empty input is skipped, but invalid configuration is still reported.
Example ¶
package main
import (
"fmt"
"github.com/muonsoft/validation/validate"
)
func main() {
fmt.Println(validate.FileExtension("backup.tar.gz", "tar.gz"))
fmt.Println(validate.FileExtension("photo.jpg.exe", "jpg"))
}
Output: <nil> invalid file extension
func FileName ¶ added in v0.20.0
func FileName(name string, options ...func(*FileNameOptions)) error
FileName validates a name, not a path. Empty names are skipped. Invalid UTF-8, control characters, separators, dot entries and drive prefixes are rejected. Input is never decoded, normalized or trimmed. Length and storage safety are separate concerns. WithWindowsFileNameRestrictions adds portable restrictions.
Example ¶
package main
import (
"fmt"
"github.com/muonsoft/validation/validate"
)
func main() {
fmt.Println(validate.FileName("отчёт.pdf"))
fmt.Println(validate.FileName("NUL.txt", validate.WithWindowsFileNameRestrictions()))
}
Output: <nil> invalid file name
func IBAN ¶ added in v0.20.0
IBAN validates whether the value is a valid International Bank Account Number. Spaces (including U+00A0 and U+202F), ASCII letters, and digits are accepted; letters are normalized to upper case.
Empty string is considered valid (use [NotBlank] or similar to reject empty values).
Possible errors:
- ErrInvalidIBAN when the value fails any IBAN rule (invalid characters, country, format, check digits, or mod-97).
See https://en.wikipedia.org/wiki/International_Bank_Account_Number.
Example ¶
package main
import (
"fmt"
"github.com/muonsoft/validation/validate"
)
func main() {
fmt.Println(validate.IBAN("DE89370400440532013000"))
fmt.Println(validate.IBAN("DE89370400440532013001"))
fmt.Println(validate.IBAN("US64SVBX1101057138"))
}
Output: <nil> invalid IBAN invalid IBAN
func IP ¶
IP validates that a value is a valid IP address (IPv4 or IPv6). You can use a list of restrictions to additionally check for a restricted range of IPs. For example, you can deny using private IP addresses using DenyPrivateIP function.
If value is not valid the function will return one of the errors:
- ErrInvalid on invalid IP address;
- ErrProhibited on restricted IP address.
Example ¶
package main
import (
"fmt"
"github.com/muonsoft/validation/validate"
)
func main() {
fmt.Println(validate.IP("123.123.123.123")) // valid IPv4
fmt.Println(validate.IP("2001:0db8:85a3:0000:0000:8a2e:0370:7334")) // valid IPv6
fmt.Println(validate.IP("123.123.123.345")) // invalid
fmt.Println(validate.IP("192.168.1.0")) // non-restricted private IP
fmt.Println(validate.IP("192.168.1.0", validate.DenyPrivateIP())) // restricted private IP
}
Output: <nil> <nil> invalid <nil> prohibited
func IPv4 ¶
IPv4 validates that a value is a valid IPv4 address. You can use a list of restrictions to additionally check for a restricted range of IPs. For example, you can deny using private IP addresses using DenyPrivateIP function.
If value is not valid the function will return one of the errors:
- ErrInvalid on invalid IP address or when using IPv6;
- ErrProhibited on restricted IP address.
Example ¶
package main
import (
"fmt"
"github.com/muonsoft/validation/validate"
)
func main() {
fmt.Println(validate.IPv4("123.123.123.123")) // valid IPv4
fmt.Println(validate.IPv4("2001:0db8:85a3:0000:0000:8a2e:0370:7334")) // invalid (IPv6)
fmt.Println(validate.IPv4("123.123.123.345")) // invalid
fmt.Println(validate.IPv4("192.168.1.0")) // non-restricted private IP
fmt.Println(validate.IPv4("192.168.1.0", validate.DenyPrivateIP())) // restricted private IP
}
Output: <nil> invalid invalid <nil> prohibited
func IPv6 ¶
IPv6 validates that a value is a valid IPv6 address. You can use a list of restrictions to additionally check for a restricted range of IPs. For example, you can deny using private IP addresses using DenyPrivateIP function.
If value is not valid the function will return one of the errors:
- ErrInvalid on invalid IP address or when using IPv4;
- ErrProhibited on restricted IP address.
Example ¶
package main
import (
"fmt"
"github.com/muonsoft/validation/validate"
)
func main() {
fmt.Println(validate.IPv6("2001:0db8:85a3:0000:0000:8a2e:0370:7334")) // valid (IPv6)
fmt.Println(validate.IPv6("123.123.123.123")) // invalid IPv4
fmt.Println(validate.IPv6("z001:0db8:85a3:0000:0000:8a2e:0370:7334")) // invalid
fmt.Println(validate.IPv6("fdfe:dcba:9876:ffff:fdc6:c46b:bb8f:7d4c")) // non-restricted private IP
fmt.Println(validate.IPv6("fdfe:dcba:9876:ffff:fdc6:c46b:bb8f:7d4c", validate.DenyPrivateIP())) // restricted private IP
}
Output: <nil> invalid invalid <nil> prohibited
func ISBN ¶ added in v0.20.0
func ISBN(value string, options ...func(*ISBNOptions)) error
ISBN validates whether the value is a valid ISBN-10 or ISBN-13. Hyphens (U+002D) are stripped; other characters are not allowed in the canonical form. Behavior is aligned with Symfony\Component\Validator\Constraints\Isbn and IsbnValidator.
Empty string is considered valid (use [NotBlank] or similar to reject empty values).
Possible errors:
- ErrISBNInvalidCharacters, ErrISBNTooShort, ErrISBNTooLong, ErrISBNChecksumFailed for the selected type;
- ErrISBNTypeNotRecognized in "any" mode when the length is between 11 and 12 digits.
See https://en.wikipedia.org/wiki/ISBN.
Example ¶
package main
import (
"fmt"
"github.com/muonsoft/validation/validate"
)
func main() {
fmt.Println(validate.ISBN("978-0451225245"))
fmt.Println(validate.ISBN("978272344228"))
fmt.Println(validate.ISBN("1234567890", validate.ISBNOnly10()))
}
Output: <nil> ISBN type not recognized ISBN checksum failed
func ISBNOnly10 ¶ added in v0.20.0
func ISBNOnly10() func(*ISBNOptions)
ISBNOnly10 restricts validation to ISBN-10 (Symfony Isbn::ISBN_10).
func ISBNOnly13 ¶ added in v0.20.0
func ISBNOnly13() func(*ISBNOptions)
ISBNOnly13 restricts validation to ISBN-13 (Symfony Isbn::ISBN_13).
func ISIN ¶ added in v0.20.0
ISIN validates whether the value is a valid International Securities Identification Number (ISIN). Letters are treated case-insensitively (normalized to upper case for validation), matching Symfony\Component\Validator\Constraints\Isin.
Possible errors:
- ErrTooShort on values with length less than 12;
- ErrTooLong on values with length greater than 12;
- ErrInvalidCharacters on values that do not match the ISIN pattern;
- ErrInvalidChecksum when the check digit is wrong;
See https://en.wikipedia.org/wiki/International_Securities_Identification_Number.
Example ¶
package main
import (
"fmt"
"github.com/muonsoft/validation/validate"
)
func main() {
fmt.Println(validate.ISIN("US0378331005"))
fmt.Println(validate.ISIN("US037833100"))
fmt.Println(validate.ISIN("123456789101"))
fmt.Println(validate.ISIN("XS2012239364"))
}
Output: <nil> too short invalid characters invalid checksum
func ISSN ¶ added in v0.20.0
ISSN validates whether the value is a valid International Standard Serial Number (ISSN). The check digit uses the ISO 3297 mod 11 algorithm (weights 8…2 on the first seven digits). An optional hyphen is allowed between the two four-character groups, matching Symfony\Component\Validator\Constraints\Issn.
Possible errors:
- ErrTooShort when fewer than eight digits/check characters remain after removing hyphens;
- ErrTooLong when more than eight remain;
- ErrInvalidCharacters when the format is not NNNN-NNNC (with optional hyphen) or digits are invalid;
- ErrInvalidChecksum when the check character is wrong;
See https://www.issn.org/understanding-the-issn/what-is-an-issn/ and ISO 3297.
Example ¶
package main
import (
"fmt"
"github.com/muonsoft/validation/validate"
)
func main() {
fmt.Println(validate.ISSN("0317-8471"))
fmt.Println(validate.ISSN("0317-847"))
fmt.Println(validate.ISSN("123-45678"))
fmt.Println(validate.ISSN("0317-8470"))
}
Output: <nil> too short invalid characters invalid checksum
func LUHN ¶ added in v0.20.0
LUHN validates whether the value passes the Luhn (mod 10) checksum. The string must contain only ASCII digits (0–9); spaces and other characters are not stripped, matching Symfony\Component\Validator\Constraints\Luhn.
Empty string is considered valid (use [NotBlank] or similar to reject empty values).
Possible errors:
- ErrContainsNonDigit when the value contains a non-digit character;
- ErrInvalidChecksum when the checksum is invalid or the value is all zeros (checksum 0).
See https://en.wikipedia.org/wiki/Luhn_algorithm.
Example ¶
package main
import (
"fmt"
"github.com/muonsoft/validation/validate"
)
func main() {
fmt.Println(validate.LUHN("79927398713"))
fmt.Println(validate.LUHN("79927398710"))
fmt.Println(validate.LUHN("12345a"))
}
Output: <nil> invalid checksum contains non-digit
func Language ¶ added in v0.20.0
Language validates a standalone two- or three-letter language code using language.ParseBase. It returns nil for an empty or valid value, otherwise ErrInvalidLanguage. Case is ignored; whitespace and composite tags such as en-US or zh-Hant are rejected. Use Locale for composite tags.
Use it for language metadata, not to assert that a translation is available. All codes recognized by x/text are accepted, including legacy codes, special codes such as und (undetermined), mul (multiple languages), zxx (no linguistic content), and the reserved private-use range qaa-qtz. It does not restrict input to living languages. Values are not modified; data follows the x/text version.
Example ¶
package main
import (
"fmt"
"github.com/muonsoft/validation/validate"
)
func main() {
fmt.Println(validate.Language("eng"))
fmt.Println(validate.Language("en-US"))
}
Output: <nil> invalid language
func Locale ¶ added in v0.20.0
Locale validates a locale identifier using language.Parse. It returns nil for an empty value or a successful parse, otherwise ErrInvalidLocale, even if the parser recovered a partial tag. It accepts BCP 47 tags and the Unicode locale forms supported by x/text, including underscore separators. Case is ignored; surrounding whitespace is not trimmed. Values are not modified.
Use it for locale preferences such as en, en-US, or zh-Hant-TW. A region is optional; numeric regions, recognized legacy tags, und, root, private-use tags, and extensions are accepted. Unlike Language, it accepts composite tags; unlike Country, its region need not identify a country.
Acceptance does not guarantee translations, formatting resources, or meaningful combinations of subtags. Extension values follow the parser's checks, not an application allowlist (for example, en-u-ca-foobar passes). Accepted identifiers follow the x/text version, not Symfony's locale list. Use a separate allowlist to enforce application support.
Example ¶
package main
import (
"fmt"
"github.com/muonsoft/validation/validate"
)
func main() {
fmt.Println(validate.Locale("zh_Hant_TW"))
fmt.Println(validate.Locale("en--US"))
}
Output: <nil> invalid locale
func MIMEType ¶ added in v0.20.0
MIMEType validates concrete type/subtype metadata, optionally against allowed types. Valid parameters are ignored in comparisons. Allowlist entries must have no parameters or wildcards. Empty input is skipped, even with an allowlist; invalid configuration is always reported. No aliases are resolved.
Example ¶
package main
import (
"fmt"
"github.com/muonsoft/validation/validate"
)
func main() {
fmt.Println(validate.MIMEType("text/plain; charset=utf-8", "text/plain"))
fmt.Println(validate.MIMEType("attachment"))
}
Output: <nil> invalid MIME type
func MacAddress ¶ added in v0.20.0
func MacAddress(value string, options ...func(*MacAddressOptions)) error
MacAddress validates that value is a 48-bit IEEE 802 MAC address accepted by net.ParseMAC (colon, hyphen, or dot-separated forms), then applies the Symfony MacAddress "type" rules on the first octet’s I/G and U/L bits and on the broadcast address ff:ff:ff:ff:ff:ff.
Returns ErrInvalidMAC when the string is not a 48-bit MAC, when it is not parseable, or when an unknown type name was set via WithMacAddressType.
Example ¶
package main
import (
"fmt"
"github.com/muonsoft/validation/validate"
)
func main() {
fmt.Println(validate.MacAddress("00:1a:2b:3c:4d:5e"))
fmt.Println(validate.MacAddress("not-mac"))
fmt.Println(validate.MacAddress("ff:ff:ff:ff:ff:ff", validate.WithMacAddressType(validate.MacAddressTypeAllNoBroadcast)))
}
Output: <nil> invalid MAC address invalid MAC address
func NoSuspiciousCharacters ¶ added in v0.20.0
func NoSuspiciousCharacters(value string, options ...NoSuspiciousCharactersOption) error
NoSuspiciousCharacters reports whether value is free of common spoofing patterns (homoglyphs, invisible characters, mixed-script digits, risky combining sequences). Empty and whitespace-only strings are valid.
Semantics are inspired by Symfony’s NoSuspiciousCharacters (ICU Spoofchecker) but implemented with the Go standard library and golang.org/x/text/language only; results may differ from ICU for edge cases.
Possible errors:
- ErrSuspiciousInvisible
- ErrSuspiciousMixedNumbers
- ErrSuspiciousHiddenOverlay
- ErrSuspiciousRestriction
Example ¶
package main
import (
"fmt"
"github.com/muonsoft/validation/validate"
)
func main() {
fmt.Println(validate.NoSuspiciousCharacters("ok"))
fmt.Println(validate.NoSuspiciousCharacters("8৪"))
fmt.Println(validate.NoSuspiciousCharacters("8৪", validate.WithSuspiciousChecks(0)))
}
Output: <nil> suspicious mixed digit scripts <nil>
func PasswordStrength ¶ added in v0.20.0
func PasswordStrength(password string, options ...func(*PasswordStrengthOptions)) error
PasswordStrength validates a password's score, defaulting to Medium. Empty strings are evaluated (score 0 by default), not skipped. It returns ErrPasswordTooWeak, ErrInvalidPasswordStrengthMinimum, or ErrInvalidPasswordStrengthScore on failure. Errors never contain the password.
Example ¶
package main
import (
"fmt"
"github.com/muonsoft/validation/validate"
)
func main() {
fmt.Println(validate.PasswordStrength("Reasonable-pwd"))
}
Output: <nil>
func RestrictURLHostByPattern ¶ added in v0.14.0
RestrictURLHostByPattern make URL validation accepts only a value with a host matching by pattern.
func RestrictURLHosts ¶ added in v0.14.0
RestrictURLHosts make URL validation accepts only the listed hosts.
func RestrictURLSchemas ¶ added in v0.14.0
RestrictURLSchemas make URL validation accepts only the listed schemas.
func Timezone ¶ added in v0.20.0
func Timezone(value string, options ...func(*TimezoneOptions)) error
Timezone validates whether the value is a known IANA timezone identifier.
Validation uses a bundled list from IANA tzdata 2026c, independent of system timezone files and ZONEINFO. It accepts "UTC" and names containing "/" (e.g. "Europe/Berlin", "Etc/GMT+5"), including legacy aliases such as "US/Eastern". Implementation-specific names such as "Local", bare abbreviations (e.g. "EST"), and unknown identifiers are rejected.
Empty string is considered valid (use [NotBlank] or similar to reject empty values).
Possible errors:
- ErrInvalidTimezone when the string is unknown, not IANA-shaped, or outside the configured zone.
Example ¶
package main
import (
"fmt"
"github.com/muonsoft/validation/validate"
)
func main() {
fmt.Println(validate.Timezone("Europe/Berlin"))
fmt.Println(validate.Timezone("EST"))
fmt.Println(validate.Timezone("America/Chicago", validate.WithTimezoneZone(validate.TimezoneZoneAmerica)))
}
Output: <nil> invalid timezone <nil>
func ULID ¶ added in v0.17.0
ULID validates whether the value is a valid ULID (Universally Unique Lexicographically Sortable Identifier). See https://github.com/ulid/spec for ULID specifications.
Possible errors:
- ErrTooShort on values with length less than 26;
- ErrTooLong on values with length greater than 26;
- ErrInvalidCharacters on values with unexpected characters;
- ErrTooLarge on too big value (larger than '7ZZZZZZZZZZZZZZZZZZZZZZZZZ').
Example ¶
package main
import (
"fmt"
"github.com/muonsoft/validation/validate"
)
func main() {
fmt.Println(validate.ULID("01ARZ3NDEKTSV4RRFFQ69G5FAV"))
fmt.Println(validate.ULID("01ARZ3NDEKTSV4RRFFQ69G5FA"))
fmt.Println(validate.ULID("01ARZ3NDEKTSV4RRFFQ69G5FAVA"))
fmt.Println(validate.ULID("01ARZ3NDEKTSV4RRFFQ69G5FAO"))
fmt.Println(validate.ULID("81ARZ3NDEKTSV4RRFFQ69G5FAV"))
}
Output: <nil> too short too long invalid characters too large
func UPCA ¶ added in v0.8.0
UPCA checks that string contains valid UPC-A code.
If the value is not valid then one of the errors will be returned:
- ErrOnlyZeros if code contains only zeros;
- ErrInvalidChecksum if check digit is not valid;
- ErrUnexpectedLength if value length has an unexpected size;
- ErrContainsNonDigit if string contains non-digit value.
See https://en.wikipedia.org/wiki/Universal_Product_Code.
Example ¶
package main
import (
"fmt"
"github.com/muonsoft/validation/validate"
)
func main() {
fmt.Println(validate.UPCA("614141000036"))
fmt.Println(validate.UPCA("000000000000"))
fmt.Println(validate.UPCA("61414100003"))
fmt.Println(validate.UPCA("A14141000036"))
fmt.Println(validate.UPCA("614141000037"))
}
Output: <nil> contains only zeros unexpected length contains non-digit: 'A' invalid checksum
func UPCE ¶ added in v0.8.0
UPCE checks that string contains valid UPC-E code.
If the value is not valid then one of the errors will be returned:
- ErrOnlyZeros if code contains only zeros;
- ErrInvalid if 8-digits code starts with number not equal to 0;
- ErrInvalidChecksum if check digit is not valid;
- ErrUnexpectedLength if value length has an unexpected size;
- ErrContainsNonDigit if string contains non-digit value.
See https://en.wikipedia.org/wiki/Universal_Product_Code#UPC-E.
Example ¶
package main
import (
"fmt"
"github.com/muonsoft/validation/validate"
)
func main() {
fmt.Println(validate.UPCE("123456")) // 6-digit is always valid
fmt.Println(validate.UPCE("1234505")) // 7-digit with last check digit
fmt.Println(validate.UPCE("01234505")) // 8-digit with first zero and last check digit
fmt.Println(validate.UPCE("00000000"))
fmt.Println(validate.UPCE("11234505"))
fmt.Println(validate.UPCE("01234501"))
fmt.Println(validate.UPCE("023456731"))
fmt.Println(validate.UPCE("A2345673"))
fmt.Println(validate.UPCE("12345"))
}
Output: <nil> <nil> <nil> contains only zeros invalid invalid checksum unexpected length contains non-digit: 'A' unexpected length
func URL ¶
URL is used to validate that value is a valid URL string. You can use a list of restrictions to additionally check for a restricted set of URLs. By default, if no restrictions are passed, the function checks for the http:// and https:// schemas.
Use the callable option to configure the list of expected schemas. If an empty string is passed as a schema, then URL value may be treated as relative (without schema, e.g. "//example.com").
Use the RestrictURLHosts or RestrictURLHostByPattern option to configure the list of allowed hosts.
If value is not a valid URL the function will return one of the errors:
- parsing error from net/url.Parse method if value cannot be parsed as a URL;
- ErrRestrictedSchema if schema is not matching one of the listed schemas;
- ErrRestrictedHost if host is not matching one of the listed hosts;
- ErrInvalid if value is not matching the regular expression.
Example ¶
package main
import (
"fmt"
"regexp"
"github.com/muonsoft/validation/validate"
)
func main() {
fmt.Println(validate.URL("https://example.com")) // valid absolute URL
fmt.Println(validate.URL("ftp://example.com", validate.RestrictURLSchemas("http", "https", "ftp"))) // valid URL with custom schema
fmt.Println(validate.URL("example.com")) // url without schema
fmt.Println(validate.URL("http:// example.com/")) // invalid URL
fmt.Println(validate.URL("//example.com", validate.RestrictURLSchemas(""))) // valid relative URL
fmt.Println(validate.URL("http://example.com", validate.RestrictURLHosts("sample.com"))) // not matching host
fmt.Println( // matching by regexp
validate.URL(
"http://sub.example.com",
validate.RestrictURLHostByPattern(regexp.MustCompile(`^.*\.example\.com$`)),
),
)
}
Output: <nil> <nil> restricted schema parse "http:// example.com/": invalid character " " in host name <nil> restricted host <nil>
func UTF8 ¶ added in v0.20.0
UTF8 returns ErrInvalidUTF8 if value contains malformed UTF-8, otherwise nil. The empty string is valid.
Go strings can contain arbitrary bytes. Use this check at input boundaries, such as file imports or legacy integrations, to reject truncated or malformed text before storage or processing that might reject or replace invalid bytes.
This checks UTF-8 only, unlike Symfony's configurable Charset constraint. It does not detect or convert other encodings, normalize text, or validate its meaning or safety. Validly encoded mojibake, U+FFFD, invisible characters, and HTML are accepted. Validate the original bytes before decoding replaces malformed sequences; such replacements cannot be detected by this check.
Example ¶
package main
import (
"fmt"
"github.com/muonsoft/validation/validate"
)
func main() {
fmt.Println(validate.UTF8("日本語"))
fmt.Println(validate.UTF8("\xe2\x82"))
}
Output: <nil> invalid UTF-8
func UUID ¶ added in v0.17.0
func UUID(value string, options ...func(o *UUIDOptions)) error
UUID validates whether a string value is a valid UUID (also known as GUID).
By default, it uses strict mode and checks the UUID as specified in RFC 4122. To parse additional formats, use the AllowNonCanonicalUUIDFormats option.
In addition, it checks if the UUID version matches one of the registered versions: 1, 2, 3, 4, 5, 6 or 7. Use AllowUUIDVersions to validate for a specific set of versions.
Nil UUID ("00000000-0000-0000-0000-000000000000") values are considered as valid. Use DenyNilUUID to disallow nil value.
Possible errors:
- ErrTooShort on values with length less than 36 (or 32 for non-canonical formats);
- ErrTooLong on values with length greater than 36 (or 45 for non-canonical formats);
- ErrInvalidCharacters on values with unexpected characters;
- ErrInvalidHyphenPlacement on invalid placements of hyphens;
- ErrInvalidVersion on a restricted versions;
- ErrIsNil on nil value (if DenyNilUUID options is enabled);
- ErrInvalid on other cases;
See http://tools.ietf.org/html/rfc4122.
Example ¶
package main
import (
"fmt"
"github.com/muonsoft/validation/validate"
)
func main() {
fmt.Println(validate.UUID("83eab6fd-230b-44fe-b52f-463387bd8788")) // v4
fmt.Println(validate.UUID("83eab6fd-230b-44fe-b52f-463387bd8788", validate.AllowUUIDVersions(4))) // v4
fmt.Println(validate.UUID("00000000-0000-0000-0000-000000000000")) // nil UUID
fmt.Println(validate.UUID("00000000-0000-0000-0000-000000000000", validate.DenyNilUUID())) // deny nil UUID
fmt.Println(validate.UUID("x3eab6fd-230b-44fe-b52f-463387bd8788")) // invalid
fmt.Println(validate.UUID("216fff40-98d9-f1e3-a5e2-0800200c9a66")) // invalid version
fmt.Println(validate.UUID("216fff4098d911e3a5e20800200c9a66")) // non-canonical
fmt.Println(validate.UUID("216fff4098d911e3a5e20800200c9a66", validate.AllowNonCanonicalUUIDFormats())) // non-canonical
}
Output: <nil> <nil> <nil> is nil invalid invalid version too short <nil>
func Week ¶ added in v0.20.0
func Week(value string, options ...func(*WeekOptions)) error
Week validates an ISO week in YYYY-Www format, using literal years 0000–9999 in the proleptic Gregorian calendar. Week 53 must exist in the specified year. Empty values are valid; use [NotBlank] to require a value. Invalid options return ErrInvalidWeekBounds, even for empty input. Other failures return ErrInvalidWeekFormat, ErrInvalidWeekNumber, ErrWeekTooEarly, or ErrWeekTooLate.
Example ¶
package main
import (
"fmt"
"github.com/muonsoft/validation/validate"
)
func main() {
fmt.Println(validate.Week("2020-W53"))
fmt.Println(validate.Week("2021-W53"))
}
Output: <nil> invalid week number
func WithContentTypeDetector ¶ added in v0.20.0
func WithContentTypeDetector(detector ContentTypeDetector) func(*ContentTypeOptions)
WithContentTypeDetector replaces detection. Nil restores http.DetectContentType. Custom detectors receive the entire supplied slice without truncation.
func WithMacAddressType ¶ added in v0.20.0
func WithMacAddressType(t MacAddressType) func(*MacAddressOptions)
WithMacAddressType sets the Symfony-compatible MAC class filter (default MacAddressTypeAll).
func WithMaxWeek ¶ added in v0.20.0
func WithMaxWeek(value string) func(*WeekOptions)
WithMaxWeek sets the inclusive maximum in YYYY-Www format. Empty removes the bound.
func WithMinPasswordStrength ¶ added in v0.20.0
func WithMinPasswordStrength(score PasswordStrengthScore) func(*PasswordStrengthOptions)
WithMinPasswordStrength sets the inclusive minimum score (1–4). Default is Medium.
func WithMinWeek ¶ added in v0.20.0
func WithMinWeek(value string) func(*WeekOptions)
WithMinWeek sets the inclusive minimum in YYYY-Www format. Empty removes the bound.
func WithPasswordStrengthEstimator ¶ added in v0.20.0
func WithPasswordStrengthEstimator(estimator PasswordStrengthEstimator) func(*PasswordStrengthOptions)
WithPasswordStrengthEstimator replaces the estimator. Nil restores the default.
func WithTimezoneZone ¶ added in v0.20.0
func WithTimezoneZone(zone TimezoneZone) func(*TimezoneOptions)
WithTimezoneZone sets the geographical region filter (default TimezoneZoneAll).
func WithWindowsFileNameRestrictions ¶ added in v0.20.0
func WithWindowsFileNameRestrictions() func(*FileNameOptions)
WithWindowsFileNameRestrictions enables conservative Windows name restrictions on every operating system. It does not impose filesystem length limits.
Types ¶
type BICOptions ¶ added in v0.20.0
type BICOptions struct {
// contains filtered or unexported fields
}
BICOptions configures BIC validation.
type CIDROptions ¶ added in v0.20.0
type CIDROptions struct {
// contains filtered or unexported fields
}
CIDROptions configures CIDR validation.
type CSSColorFormat ¶ added in v0.20.0
type CSSColorFormat string
CSSColorFormat selects one of the CSS color syntaxes supported by Symfony 8.0.
const ( // CSSColorHexLong selects the hex_long format. CSSColorHexLong CSSColorFormat = "hex_long" // CSSColorHexLongWithAlpha selects the hex_long_with_alpha format. CSSColorHexLongWithAlpha CSSColorFormat = "hex_long_with_alpha" // CSSColorHexShort selects the hex_short format. CSSColorHexShort CSSColorFormat = "hex_short" // CSSColorHexShortWithAlpha selects the hex_short_with_alpha format. CSSColorHexShortWithAlpha CSSColorFormat = "hex_short_with_alpha" // CSSColorBasicNamedColors selects the basic_named_colors format. CSSColorBasicNamedColors CSSColorFormat = "basic_named_colors" // CSSColorExtendedNamedColors selects the extended_named_colors format. CSSColorExtendedNamedColors CSSColorFormat = "extended_named_colors" // CSSColorSystemColors selects the system_colors format. CSSColorSystemColors CSSColorFormat = "system_colors" // CSSColorKeywords selects the keywords format. CSSColorKeywords CSSColorFormat = "keywords" // CSSColorRGB selects the rgb format. CSSColorRGB CSSColorFormat = "rgb" // CSSColorRGBA selects the rgba format. CSSColorRGBA CSSColorFormat = "rgba" // CSSColorHSL selects the hsl format. CSSColorHSL CSSColorFormat = "hsl" // CSSColorHSLA selects the hsla format. CSSColorHSLA CSSColorFormat = "hsla" )
type CardSchemeName ¶ added in v0.20.0
type CardSchemeName string
CardSchemeName identifies a supported payment card numbering scheme.
const ( // CardSchemeAMEX selects the AMEX numbering rules from Symfony 8.0. CardSchemeAMEX CardSchemeName = "AMEX" // CardSchemeChinaUnionPay selects the CHINA_UNIONPAY numbering rules from Symfony 8.0. CardSchemeChinaUnionPay CardSchemeName = "CHINA_UNIONPAY" // CardSchemeDiners selects the DINERS numbering rules from Symfony 8.0. CardSchemeDiners CardSchemeName = "DINERS" // CardSchemeDiscover selects the DISCOVER numbering rules from Symfony 8.0. CardSchemeDiscover CardSchemeName = "DISCOVER" // CardSchemeInstaPayment selects the INSTAPAYMENT numbering rules from Symfony 8.0. CardSchemeInstaPayment CardSchemeName = "INSTAPAYMENT" // CardSchemeJCB selects the JCB numbering rules from Symfony 8.0. CardSchemeJCB CardSchemeName = "JCB" // CardSchemeLaser selects the LASER numbering rules from Symfony 8.0. CardSchemeLaser CardSchemeName = "LASER" // CardSchemeMaestro selects the MAESTRO numbering rules from Symfony 8.0. CardSchemeMaestro CardSchemeName = "MAESTRO" // CardSchemeMastercard selects the MASTERCARD numbering rules from Symfony 8.0. CardSchemeMastercard CardSchemeName = "MASTERCARD" // CardSchemeMIR selects the MIR numbering rules from Symfony 8.0. CardSchemeMIR CardSchemeName = "MIR" // CardSchemeUATP selects the UATP numbering rules from Symfony 8.0. CardSchemeUATP CardSchemeName = "UATP" // CardSchemeVisa selects the VISA numbering rules from Symfony 8.0. CardSchemeVisa CardSchemeName = "VISA" )
type ContentTypeDetector ¶ added in v0.20.0
ContentTypeDetector identifies content without modifying data. Shared detectors must support concurrent calls. Results must be concrete MIME types; parameters are allowed. Detection does not establish file integrity or safety.
type ContentTypeOptions ¶ added in v0.20.0
type ContentTypeOptions struct {
// contains filtered or unexported fields
}
ContentTypeOptions configures content detection.
type FileNameOptions ¶ added in v0.20.0
type FileNameOptions struct {
// contains filtered or unexported fields
}
FileNameOptions configures file name validation.
type ISBNOptions ¶ added in v0.20.0
type ISBNOptions struct {
// contains filtered or unexported fields
}
ISBNOptions configures ISBN.
type ISBNType ¶ added in v0.20.0
type ISBNType int
ISBNType selects which ISBN format to validate, matching Symfony Isbn "type".
type MacAddressOptions ¶ added in v0.20.0
type MacAddressOptions struct {
Type MacAddressType
}
MacAddressOptions configures MacAddress validation (Symfony MacAddress "type").
type MacAddressType ¶ added in v0.20.0
type MacAddressType string
MacAddressType represents Symfony\Component\Validator\Constraints\MacAddress "type".
const ( MacAddressTypeAll MacAddressType = "all" MacAddressTypeAllNoBroadcast MacAddressType = "all_no_broadcast" MacAddressTypeLocalAll MacAddressType = "local_all" MacAddressTypeLocalNoBroadcast MacAddressType = "local_no_broadcast" MacAddressTypeLocalUnicast MacAddressType = "local_unicast" MacAddressTypeLocalMulticast MacAddressType = "local_multicast" MacAddressTypeLocalMulticastNoBroadcast MacAddressType = "local_multicast_no_broadcast" MacAddressTypeUniversalAll MacAddressType = "universal_all" MacAddressTypeUniversalUnicast MacAddressType = "universal_unicast" MacAddressTypeUniversalMulticast MacAddressType = "universal_multicast" MacAddressTypeUnicastAll MacAddressType = "unicast_all" MacAddressTypeMulticastAll MacAddressType = "multicast_all" MacAddressTypeMulticastNoBroadcast MacAddressType = "multicast_no_broadcast" MacAddressTypeBroadcast MacAddressType = "broadcast" )
MAC address type values match Symfony\Component\Validator\Constraints\MacAddress.
type NoSuspiciousCharactersOption ¶ added in v0.20.0
type NoSuspiciousCharactersOption func(*NoSuspiciousCharactersOptions)
NoSuspiciousCharactersOption mutates NoSuspiciousCharactersOptions.
func WithSuspiciousChecks ¶ added in v0.20.0
func WithSuspiciousChecks(checks uint) NoSuspiciousCharactersOption
WithSuspiciousChecks sets the bitmask of checks (Symfony-compatible values). Zero means “use default all checks”.
func WithSuspiciousLocales ¶ added in v0.20.0
func WithSuspiciousLocales(locales ...string) NoSuspiciousCharactersOption
WithSuspiciousLocales sets BCP 47 locale tags used for SuspiciousRestrictionLocales (e.g. "en", "en-US").
func WithSuspiciousRestriction ¶ added in v0.20.0
func WithSuspiciousRestriction(r SuspiciousRestriction) NoSuspiciousCharactersOption
WithSuspiciousRestriction sets locale/script restriction mode.
type NoSuspiciousCharactersOptions ¶ added in v0.20.0
type NoSuspiciousCharactersOptions struct {
Checks uint
Restriction SuspiciousRestriction
Locales []string
// contains filtered or unexported fields
}
NoSuspiciousCharactersOptions configures NoSuspiciousCharacters.
type PasswordStrengthEstimator ¶ added in v0.20.0
type PasswordStrengthEstimator func(string) PasswordStrengthScore
PasswordStrengthEstimator evaluates a password. It must return a score from 0 to 4. Implementations used concurrently must be safe for concurrent calls.
type PasswordStrengthOptions ¶ added in v0.20.0
type PasswordStrengthOptions struct {
// contains filtered or unexported fields
}
PasswordStrengthOptions configures the minimum and optional custom estimator.
type PasswordStrengthScore ¶ added in v0.20.0
type PasswordStrengthScore int
PasswordStrengthScore is a heuristic score from 0 (very weak) to 4 (very strong).
const ( // PasswordStrengthVeryWeak is the lowest score, including empty passwords. PasswordStrengthVeryWeak PasswordStrengthScore = iota // PasswordStrengthWeak corresponds to an entropy estimate of at least 60. PasswordStrengthWeak // PasswordStrengthMedium corresponds to an entropy estimate of at least 80. PasswordStrengthMedium // PasswordStrengthStrong corresponds to an entropy estimate of at least 100. PasswordStrengthStrong // PasswordStrengthVeryStrong corresponds to an entropy estimate of at least 120. PasswordStrengthVeryStrong )
func EstimatePasswordStrength ¶ added in v0.20.0
func EstimatePasswordStrength(password string) PasswordStrengthScore
EstimatePasswordStrength reproduces Symfony 8.0's byte-based heuristic. It uses byte length, unique byte count, and character category pool sizes. No Unicode normalization, dictionary, sequence detection, or breach lookup is performed. The score is not a guarantee of resistance to password guessing. Empty input returns VeryWeak. Runtime is O(len(password)), memory is O(1). See https://github.com/symfony/validator/blob/8.0/Constraints/PasswordStrengthValidator.php.
Example ¶
package main
import (
"fmt"
"github.com/muonsoft/validation/validate"
)
func main() {
fmt.Println(validate.EstimatePasswordStrength("Reasonable-pwd"))
}
Output: 2
type SuspiciousRestriction ¶ added in v0.20.0
type SuspiciousRestriction int
Restriction for script/locale-related validation (approximation of Symfony restriction levels).
const ( // SuspiciousRestrictionNone disables locale/script checks (like RESTRICTION_LEVEL_NONE). SuspiciousRestrictionNone SuspiciousRestriction = iota // SuspiciousRestrictionLocales restricts letters/marks to scripts associated with [NoSuspiciousCharactersOptions.Locales] // (like a moderate locale allow-list). When Locales is empty, [language.English] is used. SuspiciousRestrictionLocales // SuspiciousRestrictionSingleScript requires at most one non-Common, non-Inherited script among letters/marks/numbers. SuspiciousRestrictionSingleScript )
type TimezoneOptions ¶ added in v0.20.0
type TimezoneOptions struct {
// contains filtered or unexported fields
}
TimezoneOptions configures Timezone validation.
type TimezoneZone ¶ added in v0.20.0
type TimezoneZone string
TimezoneZone restricts valid timezone identifiers to a geographical region, aligned with Symfony\Component\Validator\Constraints\Timezone zone option (PHP \DateTimeZone::AFRICA, ::AMERICA, and similar constants).
const ( // TimezoneZoneAll accepts all identifiers in the bundled IANA timezone list. TimezoneZoneAll TimezoneZone = "" // TimezoneZoneAfrica restricts identifiers to the Africa region (e.g. "Africa/Nairobi"). TimezoneZoneAfrica TimezoneZone = "Africa" // TimezoneZoneAmerica restricts identifiers to the America region (e.g. "America/New_York"). TimezoneZoneAmerica TimezoneZone = "America" // TimezoneZoneAntarctica restricts identifiers to the Antarctica region. TimezoneZoneAntarctica TimezoneZone = "Antarctica" // TimezoneZoneArctic restricts identifiers to the Arctic region. TimezoneZoneArctic TimezoneZone = "Arctic" // TimezoneZoneAsia restricts identifiers to the Asia region (e.g. "Asia/Tokyo"). TimezoneZoneAsia TimezoneZone = "Asia" // TimezoneZoneAtlantic restricts identifiers to the Atlantic region. TimezoneZoneAtlantic TimezoneZone = "Atlantic" // TimezoneZoneAustralia restricts identifiers to the Australia region. TimezoneZoneAustralia TimezoneZone = "Australia" // TimezoneZoneEurope restricts identifiers to the Europe region (e.g. "Europe/Berlin"). TimezoneZoneEurope TimezoneZone = "Europe" // TimezoneZoneIndian restricts identifiers to the Indian Ocean region. TimezoneZoneIndian TimezoneZone = "Indian" // TimezoneZonePacific restricts identifiers to the Pacific region. TimezoneZonePacific TimezoneZone = "Pacific" )
type UUIDOptions ¶ added in v0.17.0
type UUIDOptions struct {
// contains filtered or unexported fields
}
UUIDOptions are used to set up validation process of the UUID function.
type WeekOptions ¶ added in v0.20.0
type WeekOptions struct {
// contains filtered or unexported fields
}
WeekOptions configures inclusive ISO week bounds for Week.