Documentation
¶
Overview ¶
Package is provides a comprehensive set of validation functions for data formats commonly used in web applications, financial systems, and general software development.
Overview ¶
The package offers validation functions for various data types and formats:
- Identity and Access: email addresses, nicknames, variable names;
- Financial: bank card numbers, IBAN accounts;
- Geographic: latitude/longitude coordinates;
- Network: IPv4/IPv6 addresses, MAC addresses, URLs, hostnames, domains;
- Telecommunications: phone numbers in E.164 format, IMEI/IMSI;
- String Types: alphanumeric, numeric, hexadecimal, binary;
- Numbers: even/odd, positive/negative, natural numbers;
- Encodings: Base64, Base64URL, JWT tokens;
- Data formats: MD5/SHA-1/SHA-256/SHA-512 hashes, UUID.
Design Philosophy ¶
The package follows several key principles:
- No data cleaning - functions validate data as-is without modification;
- Zero dependencies - minimal external dependencies;
- Type safety - extensive use of Go generics where appropriate;
- Performance - optimized for speed and minimal memory allocation.
Usage ¶
Most functions follow a simple pattern returning a boolean indicating validity:
if is.Email("user@example.com") {
// Valid email address
}
if is.BankCard("4111111111111111") {
// Valid bank card number
}
Some functions support additional validation modes:
// Strict mode validation
if is.Nickname("user123", true) {
// Valid nickname in strict mode
}
Data Cleaning ¶
This package does not perform data cleaning. If input needs cleaning, use appropriate tools beforehand. For example, with the companion 'g' package:
// Clean IBAN before validation
raw := "GB82 WEST 1234 5698 7654 32" // contains spaces
iban := g.Weed(raw, g.Whitespaces) // remove spaces
if is.IBAN(iban) {
// Valid IBAN
}
Common Validation Patterns ¶
Account Validation:
is.Email("user@example.com") // Email address
is.Nickname("user123") // Username
is.VariableName("myVar") // Programming variable name
Financial Validation:
is.BankCard("4111111111111111") // Bank card number
is.IBAN("DE89370400440532013000") // IBAN account number
Geographic Validation:
is.Latitude(45.423) // Latitude coordinate is.Longitude(-75.935) // Longitude coordinate
Network Address Validation:
is.IPv4("192.168.0.1") // IPv4 address
is.IPv6("2001:db8::1") // IPv6 address
is.MAC("00:1b:63:84:45:e6") // MAC address
is.URL("https://example.com") // Absolute URL
is.Hostname("example.com") // RFC 1123 hostname
is.Domain("example.com") // Domain name
Phone Number Validation:
is.E164("+1234567890") // E.164 format
is.Phone("+1 (234) 567-890") // General phone format
String Type Validation:
is.Alpha("ABC") // Alphabetic characters
is.Digit("123") // Numeric digits
is.Alnum("ABC123") // Alphanumeric characters
is.HexColor("#FF5733") // Hexadecimal color
Number Validation:
is.Even(4) // Even number is.Odd(3) // Odd number is.Natural(5) // Natural number is.Positive(1.5) // Positive number
Format Validation:
is.Base64("SGVsbG8=") // Base64 encoding
is.MD5("d41d8cd98f00b204...") // MD5 hash
is.SHA256("e3b0c44298fc...") // SHA-256 hash
is.UUID("550e8400-e29b...") // UUID
is.JWT("eyJhbGciOiJIUzI...") // JWT token
For more detailed information about specific validation functions, see their respective documentation.
Index ¶
- Variables
- func Alnum(s string) bool
- func Alpha(s string) bool
- func BankCard(str string, kinds ...CardKind) bool
- func Base64(v string) bool
- func Base64URL(v string) bool
- func Bin(v string) bool
- func CalculateIBANChecksum(iban string) int
- func Coordinates[T string | float64](lat, lon T) bool
- func Decimal(s string) bool
- func Digit(s string) bool
- func Domain(v string) bool
- func E164(v string) bool
- func Email(email string) bool
- func Even[T Numerable](v T, f ...bool) bool
- func Float(s string) bool
- func Hex(v string) bool
- func HexColor(v string) bool
- func Hostname(v string) bool
- func IBAN(iban string, strict ...bool) bool
- func IBANCountry(iban string, strict ...bool) (string, bool)
- func IMEI[T string | int64](imei T) bool
- func IMSI(imsi string) bool
- func IP(ip string) bool
- func IPv4(ip string) bool
- func IPv6(ip string) bool
- func Iban(iban string, strict ...bool) bool
- func IsToken(s string) bool
- func JWT(v string) bool
- func Latitude[T string | float64](lat T) bool
- func Longitude[T string | float64](lon T) bool
- func Lower(s string) bool
- func MAC(v string) bool
- func MD5(v string) bool
- func Natural[T Numerable](v T) bool
- func Negative[T Numerable](v T) bool
- func Nickname(nickname string, strict ...bool) bool
- func Numeric(s string) bool
- func Odd[T Numerable](v T, f ...bool) bool
- func Phone(phone string) bool
- func Positive[T Numerable](v T) bool
- func RGBColor(v string) bool
- func SHA1(v string) bool
- func SHA256(v string) bool
- func SHA512(v string) bool
- func Sel(v string, strict ...bool) bool
- func SelectorName(v string, strict ...bool) bool
- func Space(s string) bool
- func Title(s string) bool
- func TokenOctet(b byte) bool
- func URL(v string) bool
- func UUID(v string) bool
- func Upper(s string) bool
- func Var(v string, strict ...bool) bool
- func VarFor(v string, language string) (bool, error)
- func VariableName(v string, strict ...bool) bool
- func VariableNameFor(v string, language string) (bool, error)
- func Whole[T Numerable](v T) bool
- func Zero[T Numerable](v T) bool
- type CardKind
- type Numerable
- type Verifiable
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ErrLanguageNotSupported = errors.New("programming language is not supported")
ErrLanguageNotSupported is returned by VariableNameFor and VarFor when the requested programming language is not known. It is a sentinel error: test for it with errors.Is rather than by string comparison.
if _, err := is.VariableNameFor(name, lang); errors.Is(
err, is.ErrLanguageNotSupported) {
// the language is not supported
}
Functions ¶
func Alnum ¶
Alnum checks whether a string consists only of alphabetic characters (letters) and numbers.
Example usage:
is.Alnum("abc123") // Output: true
is.Alnum("abc") // Output: true
is.Alnum("123") // Output: true
is.Alnum("abc!") // Output: false
is.Alnum("abcΔ") // Output: true, Δ is a Unicode letter
func Alpha ¶
Alpha checks whether a string consists only of alphabetic characters (letters). It does not recognize digits, special characters.
Example usage:
is.Alpha("Київ") // Output: true
is.Alpha("abc") // Output: true
is.Alpha("abc1") // Output: false, contains a digit
is.Alpha("abc!") // Output: false, contains a special character
is.Alpha("abcΔ") // Output: true, Δ is a Unicode letter
func BankCard ¶
BankCard validates a bank card number, optionally restricting it to one or more card brands.
Validation always combines two independent checks: the Luhn checksum and a brand pattern. If no kind is given, the number is checked against the union of all supported brands. If one or more kinds are given, the number is valid when it passes the Luhn check AND matches at least one of them.
Spaces and hyphens in the input are ignored, so grouped numbers such as "4111 1111 1111 1111" validate the same as "4111111111111111".
Example usage:
is.BankCard("4111111111111111")
// Output: true (valid number, any brand)
is.BankCard("4111111111111111", is.MasterCard)
// Output: false (valid number, but not a MasterCard)
is.BankCard("4111111111111111", is.Visa)
// Output: true (valid Visa)
is.BankCard("4111111111111111", is.Visa, is.MasterCard)
// Output: true (matches Visa or MasterCard)
is.BankCard("1234567812345678")
// Output: false (fails the Luhn check)
Example ¶
package main
import (
"fmt"
"github.com/goloop/is/v2"
)
func main() {
fmt.Println(is.BankCard("4111111111111111")) // any brand
fmt.Println(is.BankCard("4111111111111111", is.Visa)) // as Visa
fmt.Println(is.BankCard("4111111111111111", is.MasterCard))
}
Output: true true false
func Base64 ¶
Base64 validates whether a given string 'v' is a valid Base64 encoded string.
Base64 is a binary-to-text encoding scheme that is commonly used to encode binary data, notably when that data needs to be stored and transferred over media designed to handle text. This encoding helps to ensure that the data remains intact without modification during transport.
This function uses a regular expression to verify that the input string conforms to the format of a Base64 encoded string. It checks if the string can be evenly divided by 4, and only contains valid Base64 characters (A-Z, a-z, 0-9, +, /, and = for padding). The padding at the end of Base64 string, which is one or two '=' characters, is also checked for.
If the input string matches this format, the function returns true, indicating that the string is a valid Base64 encoded string. Otherwise, it returns false.
Example usage:
is.Base64("SGVsbG8sIHdvcmxkIQ==") // Returns: true
is.Base64("SGVsbG8sIHdvcmxkIQ") // Returns: false
Note: This function does not validate the content of the encoded data, just the format of Base64 strings.
func Base64URL ¶
Base64URL validates whether a given string 'v' is a valid URL-safe Base64 encoded string.
URL-safe Base64 encoding is similar to standard Base64 encoding, but it uses different characters to represent the encoded data, making it safe to use in URLs and filenames. The characters '+' and '/' in standard Base64 encoding are replaced with '-' and '_' respectively in URL-safe Base64 encoding. The padding character '=' is also used in URL-safe Base64 encoding.
This function uses a regular expression to verify that the input string conforms to the format of a URL-safe Base64 encoded string. It checks if the string can be evenly divided by 4, and only contains valid URL-safe Base64 characters (A-Z, a-z, 0-9, -, and _ for padding). The padding at the end of URL-safe Base64 string, which is one or two '=' characters, is also checked for.
If the input string matches this format, the function returns true, indicating that the string is a valid URL-safe Base64 encoded string. Otherwise, it returns false.
Example usage:
is.Base64URL("SGVsbG8sIHdvcmxkIQ") // Returns: true
is.Base64URL("SGVsbG8sIHdvcmxkIQ==") // Returns: true
is.Base64URL("SGVsbG8sIHdvcmxkIQ===") // Returns: false
Note: This function does not validate the content of the encoded data, just the format of URL-safe Base64 strings.
func Bin ¶
Bin validates whether a given string 'v' is a valid binary value.
A binary value is a number that includes only the digits 0 and 1. Binary values are the most basic unit of data in computing and digital communications.
This function does not require '0b' prefix to be present in the input string, although it will accept strings with this prefix.
The function uses a regular expression to verify that the input string conforms to the format of a binary number.
If the input string matches this format, the function returns true, indicating that the string is a valid binary value. Otherwise, it returns false.
Example usage:
is.Bin("101010") // Returns: true
is.Bin("0b1101") // Returns: true
is.Bin("10201") // Returns: false
Note: This function does not validate semantic correctness, just the format of binary values.
func CalculateIBANChecksum ¶
CalculateIBANChecksum returns the ISO 7064 MOD-97-10 check value of the given (already rearranged) IBAN string. Each letter A-Z is expanded to its two-digit value (A=10, B=11, … Z=35) and each digit keeps its value; the remainder modulo 97 is folded incrementally, so no big integer is ever materialized and the call allocates nothing.
It returns -1 if the input contains any character outside [0-9A-Z]. A rearranged IBAN is valid precisely when this value equals 1.
func Coordinates ¶
Coordinates validates if the given pair of values represent valid geographic coordinates. The pair consists of a latitude and a longitude.
The function takes two values (float64 or string) representing the latitude and the longitude and checks if they fall within the valid ranges for their respective geographic coordinate systems.
Example usage:
is.Coordinates(45.0, -123.1) // Returns: true is.Coordinates(90.1, 180.1) // Returns: false
func Decimal ¶
Decimal returns true if all characters in the string are decimal digits and the string is not empty. Decimal digits are only the characters with the numbers 0 through 9. It does not recognize any other numeric characters such as Roman numerals or digits from non-positional number systems.
Example usage:
is.Decimal("1234") // Output: true
is.Decimal("Ⅳ") // Output: false
is.Decimal("1234abc") // Output: false
is.Decimal("1234.56") // Output: false
func Digit ¶
Digit checks whether a string consists only of numbers.
This method returns true if all characters in the string are numbers and the string is not empty. This includes digits (0-9), numeric characters that have a specific meaning in non-positional number systems (such as base 2, 8, or 16 number systems), and Unicode digit characters.
Example usage:
is.Digit("1234") // Output: true
is.Digit("Ⅳ") // Output: false
is.Digit("1234abc") // Output: false
func Domain ¶
Domain checks if the string is a valid domain name: a hostname (see Hostname) with at least two labels and a top-level domain of two or more letters. Unlike Hostname, a single label such as "localhost" and an all-numeric or one-letter TLD are rejected.
It validates the textual format only; it does not resolve the name or consult a public-suffix list.
Example usage:
is.Domain("example.com") // Returns: true
is.Domain("sub.example.com") // Returns: true
is.Domain("localhost") // Returns: false, no TLD
is.Domain("example.123") // Returns: false, numeric TLD
is.Domain("example.c") // Returns: false, one-letter TLD
is.Domain("example.xn--p1ai") // Returns: true, punycode (IDN) TLD
is.Domain("") // Returns: false, empty string
Example ¶
package main
import (
"fmt"
"github.com/goloop/is/v2"
)
func main() {
fmt.Println(is.Domain("sub.example.com"))
fmt.Println(is.Domain("localhost")) // no TLD
}
Output: true false
func E164 ¶
E164 checks if the string is a valid representation of a phone number according to the E.164 standard.
The E.164 standard defines a numbering plan for the international public telecommunication numbering system. It specifies the format for international phone numbers and assigns a unique number to each country or region.
This function uses a regular expression to match the input string against the E.164 phone number pattern. The pattern requires the string to start with a plus sign (+) followed by one or more digits. It allows a maximum length of 15 digits (excluding the plus sign).
Example usage:
is.E164("+123456789") // Returns: true
is.E164("+0123456789") // Returns: false, country code cannot start with 0
is.E164("+") // Returns: false, no digits after plus sign
is.E164("+1234567890a") // Returns: false, non-digit character
is.E164("1234567890") // Returns: false, no plus sign
is.E164("") // Returns: false, empty string
This function can be used to validate user input or data to ensure it follows the E.164 standard for phone numbers.
func Email ¶
Email validates an email address and returns a boolean result. The function checks for email length, splits the email into local and domain parts, validates the length of the local part, and finally uses regular expressions to check the format of each part.
Example usage:
is.Email("test@example.com") // Output: true
is.Email("TEST@EXAMPLE.COM") // Output: true
is.Email(" test@example.com") // Output: false
is.Email("test@example.c") // Output: false
The function performs only a format check, so it does not clean spaces at the beginning and end of a line, does not remove tab characters and carriage returns to a new line. You can use the g.Wedd and g.Trim functions for it:
is.Email(g.Trim(" test@example.com\n")) // Output: true
is.Email(g.Weed("test\t@example.com\n")) // Output: true
Example ¶
package main
import (
"fmt"
"github.com/goloop/is/v2"
)
func main() {
fmt.Println(is.Email("user@example.com"))
fmt.Println(is.Email(" user@example.com")) // not trimmed
}
Output: true false
func Even ¶
Even checks if a value is an even number.
The function accepts a value of any type T that satisfies the Numerable interface. If the `f` argument is provided and set to true, the function ignores the fractional part of the value when checking for evenness. For integer types, it checks if the value is divisible by 2 without a remainder. For floating-point types, it considers only the integer part of the value and determines the parity of the integer part. If the value has a non-zero fractional part and `f` is true, it returns false since an even number cannot have a fractional part.
Example usage:
even := is.Even(6) fmt.Println(even) // Output: true odd := is.Even(7) fmt.Println(odd) // Output: false floatingPoint := is.Even(6.6) fmt.Println(floatingPoint) // Output: false floatingPoint = is.Even(6.6, true) fmt.Println(floatingPoint) // Output: true
func Float ¶
Float returns true if the string represents a floating-point number, where the decimal separator is a dot, and all digits are ASCII digits (0-9). It supports an optional '+' or '-' sign at the beginning and at most one decimal point. It does not support exponential notation or other numeric formats.
Example usage:
is.Float("123.456") // Output: true
is.Float("-0.001") // Output: true
is.Float("3.14") // Output: true
is.Float("123") // Output: true
is.Float("123.") // Output: true
is.Float(".456") // Output: true
is.Float("123.456.789") // Output: false
is.Float("abc") // Output: false
is.Float("123a") // Output: false
is.Float("123,456") // Output: false
func Hex ¶
Hex validates whether a given string 'v' is a valid hexadecimal value.
A hexadecimal value is a number that includes digits from 0 to 9 and letters from A to F (either lower case or upper case). Hexadecimal values are often used in computing to represent numbers in a human-readable format.
This function does not require '0x' or '#' prefix to be present in the input string, although it will accept strings with these prefixes.
The function uses a regular expression to verify that the input string conforms to the format of a hexadecimal number.
If the input string matches this format, the function returns true, indicating that the string is a valid hexadecimal value. Otherwise, it returns false.
Example usage:
is.Hex("deadBEEF") // Returns: true
is.Hex("#c0ffee") // Returns: true
is.Hex("nothex") // Returns: false
Note: This function does not validate semantic correctness, just the format of hexadecimal values.
func HexColor ¶
HexColor validates whether a given string 'v' is a valid hexadecimal RGB color value. Hexadecimal RGB color values are defined as '#<color>', where <color> is either a 3-digit or a 6-digit hexadecimal number. Each digit is in the range 0-9 and A-F (either lower case or upper case).
The function uses a regular expression to verify that the input string conforms to this format.
In the case of a 3-digit color, each digit represents a color value for red, green, and blue respectively. Each digit is equivalent to repeating it twice in a 6-digit color. For example, "#123" in 3-digit color is equivalent to "#112233" in 6-digit color.
In the case of a 6-digit color, the first two digits represent red, the next two represent green, and the last two represent blue.
If the input string matches this format, the function returns true, indicating that the string is a valid hexadecimal RGB color value. Otherwise, it returns false.
Example usage:
is.HexColor("#fff") // Returns: true
is.HexColor("#efef01") // Returns: true
is.HexColor("not") // Returns: false
Note: The function does not validate color semantic correctness, just the format of hexadecimal RGB colors.
func Hostname ¶
Hostname checks if the string is a valid RFC 1123 hostname: one or more dot-separated labels of letters, digits, and hyphens, where no label starts or ends with a hyphen, each label is at most 63 characters, and the whole name is at most 253 characters.
It validates the textual format only; it does not resolve the name.
Example usage:
is.Hostname("example.com") // Returns: true
is.Hostname("sub.example.com") // Returns: true
is.Hostname("localhost") // Returns: true
is.Hostname("-bad.example") // Returns: false, label starts with '-'
is.Hostname("a..b") // Returns: false, empty label
is.Hostname("") // Returns: false, empty string
func IBAN ¶
IBAN is a synonym for the Iban function. This naming approach adheres to Go's conventions for abbreviations in function names. The function takes an IBAN (International Bank Account Number) as a string parameter and returns a boolean value indicating whether the input IBAN is valid according to the defined pattern and checksum.
Example ¶
package main
import (
"fmt"
"github.com/goloop/is/v2"
)
func main() {
fmt.Println(is.IBAN("GB82 WEST 1234 5698 7654 32")) // spaces ok
fmt.Println(is.IBAN("GB82 WEST 1234 5698 7654 32", true)) // strict: no spaces
}
Output: true false
func IBANCountry ¶
IBANCountry validates the IBAN and, if it is valid, returns its ISO 3166-1 alpha-2 country code (the first two characters) together with true. For an invalid IBAN it returns an empty string and false.
The strict parameter has the same meaning as in Iban: in non-strict mode (default) spaces are removed and letters are upper-cased before validation, so the returned country code is always upper-case.
Example usage:
is.IBANCountry("DE89370400440532013000") // Returns: "DE", true
is.IBANCountry("gb82 west 1234 5698 7654 32") // Returns: "GB", true
is.IBANCountry("DE0037040044053201300") // Returns: "", false
Example ¶
package main
import (
"fmt"
"github.com/goloop/is/v2"
)
func main() {
country, ok := is.IBANCountry("DE89370400440532013000")
fmt.Println(country, ok)
}
Output: DE true
func IMEI ¶
IMEI validates whether a given string is a valid International Mobile Equipment Identity (IMEI). It uses the Luhn algorithm for verification.
The value cannot contain characters other than numbers.
The function takes as input a string 'v' representing a potential IMEI number, which could include spaces, dots, hyphens, or newline characters as separators. These are removed from the input string to obtain the raw number.
The Luhn algorithm is then applied to this raw number to check its validity. This involves iterating over each digit in the number. If the digit is at an even-indexed position in the string (where the first position is considered index 1), its value is added directly to a running sum. If the digit is at an odd-indexed position, it is doubled. If the result of this doubling is greater than 9, 9 is subtracted from it. This resultant value is then added to the sum.
After all digits have been processed, the function checks if the total sum is a multiple of 10. If it is, the function returns true, indicating that the input string is a valid IMEI. Otherwise, it returns false.
Example usage:
is.IMEI("522593572995861") // Returns: true
is.IMEI("532593572995861") // Returns: false
Note: An IMEI number is a unique identifier assigned to each mobile device. It is a 15-digit number used for tracking and identifying the device. The last digit is a check digit, computed according to the Luhn algorithm.
func IMSI ¶
IMSI checks if the given value is a valid International Mobile Subscriber Identity (IMSI). The IMSI is a unique identifier associated with a mobile network subscriber. It consists of three parts: MCC (Mobile Country Code), MNC (Mobile Network Code), and MSIN (Mobile Subscriber Identification Number).
This function validates the IMSI structurally: it must be exactly 15 ASCII digits (0-9). The MCC, MNC, and MSIN segments are positional, but only their digit-ness is checked here, not their assignment to a real operator. A sign, space, or any non-digit makes the value invalid.
Example usage:
is.IMSI("310150123456789") // Returns: true
is.IMSI("460001234567890") // Returns: true
is.IMSI("1234567890123456") // Returns: false, length exceeds 15 digits
is.IMSI("310150abc123456") // Returns: false, invalid characters in MSIN
is.IMSI("+10150123456789") // Returns: false, sign is not a digit
func IP ¶
IP checks if the string is a valid representation of an IP address. The IP address can be either IPv4 or IPv6.
This function first checks if the string is a valid IPv4 address using the IPv4 function, if that check fails it then checks if the string is a valid IPv6 address using the IPv6 function.
Example usage:
is.IP("127.0.0.1") // Returns: true, valid IPv4
is.IP("::1") // Returns: true, valid IPv6
is.IP("2001:db8::8a2e") // Returns: true, valid IPv6
is.IP("256.0.0.1") // Returns: false, invalid IPv4
is.IP("192.168.0") // Returns: false, invalid IPv4
is.IP("2001::25de::cade") // Returns: false, invalid IPv6
is.IP("") // Returns: false, empty string
This function can be used to validate user input to ensure an IP address entered is in the correct format before attempting to use it in network operations.
func IPv4 ¶
IPv4 checks if the string is a valid representation of an IPv4 address. An IPv4 address consists of four decimal octets in the range 0-255, separated by dots (dotted-decimal notation).
Leading zeros are NOT allowed: "192.168.0.01" is rejected, because a leading zero is ambiguous (it could be read as octal) and the canonical textual form has none. This matches the parsing rules of the standard library's net/netip. Empty strings, IPv6 addresses, and strings with the wrong number of octets are not valid IPv4 addresses.
Example usage:
is.IPv4("127.0.0.1") // Returns: true
is.IPv4("192.168.0.1") // Returns: true
is.IPv4("0.0.0.0") // Returns: true
is.IPv4("255.255.255.255") // Returns: true
is.IPv4("192.168.0.01") // Returns: false, leading zero
is.IPv4("256.0.0.1") // Returns: false, octet exceeds the range
is.IPv4("192.168.0") // Returns: false, only three octets
is.IPv4("192.168.0.1.1") // Returns: false, more than four octets
is.IPv4("192.168.0.one") // Returns: false, non-numeric characters
is.IPv4("") // Returns: false, empty string
This function can be used to validate user input to ensure an IPv4 address entered is in the correct format before attempting to use it in network operations.
Example ¶
package main
import (
"fmt"
"github.com/goloop/is/v2"
)
func main() {
fmt.Println(is.IPv4("192.168.0.1"))
fmt.Println(is.IPv4("192.168.0.01")) // leading zero is rejected
}
Output: true false
func IPv6 ¶
IPv6 checks if the string is a valid representation of an IPv6 address. An IPv6 address consists of eight groups of four hexadecimal digits, each group representing 16 bits. The groups are separated by colons (:).
This function uses net/netip from the Go standard library to parse the address and then checks that it is an IPv6 address (including IPv4-mapped IPv6 addresses), which excludes plain dotted-decimal IPv4 input. A scoped address carrying a zone identifier (for example "fe80::1%eth0") is rejected: the zone is a routing scope, not part of the address itself.
Example usage:
is.IPv6("2001:0db8:85a3:0000:0000:8a2e:0370:7334") // Returns: true
is.IPv6("2001:db8:85a3:0:0:8a2e:370:7334") // Returns: true
is.IPv6("2001:db8:85a3::8a2e:370:7334") // Returns: true
is.IPv6("::1") // Returns: true
is.IPv6("::") // Returns: true
// The group "37023" exceeds 16 bits.
is.IPv6("2001:db8::8a2e:37023:7334") // Returns: false
// Only one "::" is allowed in an IPv6 address.
is.IPv6("2001::25de::cade") // Returns: false
// This is an IPv4 address.
is.IPv6("192.168.0.1") // Returns: false,
is.IPv6("") // Returns: false, empty string
This function can be used to validate user input to ensure an IPv6 address entered is in the correct format before attempting to use it in network operations.
func Iban ¶
Iban checks if a given IBAN (International Bank Account Number) has a valid format. If the input matches the pattern for the corresponding country and passes the checksum validation, the function returns true.
By default, the function operates in non-strict mode. In non-strict mode:
- Spaces are removed from the input string.
- The input string is converted to uppercase.
This allows the function to validate IBANs that may have spaces or lowercase letters.
If the optional parameter `strict` is provided and set to true, the function operates in strict mode:
- The input string is not modified.
- Any deviations from the standard IBAN format (such as spaces, lowercase letters, or special characters) will cause the function to return false.
Example usage:
// Non-strict mode (default):
is.Iban("GB82 WEST 1234 5698 7654 32") // Returns: true
is.Iban("ua903052992990004149123456789") // Returns: true
// Strict mode:
is.Iban("GB82WEST12345698765432", true) // Returns: true
is.Iban("GB82 WEST 1234 5698 7654 32", true) // Returns: false
is.Iban("ua903052992990004149123456789", true)// Returns: false (lowercase)
Note:
- In strict mode, you should ensure that the input IBAN is properly formatted:
- No spaces or special characters.
- All letters are uppercase.
- You can preprocess the IBAN before validation if needed.
For example, to validate an IBAN with spaces in strict mode:
iban := "GB82 WEST 1234 5698 7654 32" iban = strings.ReplaceAll(iban, " ", "") iban = strings.ToUpper(iban) is.Iban(iban, true) // Returns: true
func IsToken ¶ added in v2.3.1
IsToken reports whether s is a valid HTTP token: one or more token characters and nothing else (RFC 9110, section 5.6.2):
token = 1*tchar
The empty string is not a token, so IsToken("") is false. Each byte is checked with TokenOctet, so a token never contains whitespace, control bytes, non-ASCII bytes or any HTTP delimiter. This is the rule that HTTP field names and request-method names must satisfy, which makes IsToken a convenient guard when reading or forwarding those values.
is.IsToken("Content-Type") // true
is.IsToken("GET") // true
is.IsToken("a b") // false - space is a delimiter
is.IsToken("") // false - a token needs at least one octet
The check is byte-oriented on purpose: tokens are ASCII by definition, so a multi-byte UTF-8 sequence can never be a valid token and is rejected at its first non-ASCII byte.
func JWT ¶
JWT checks if the given string is a valid JSON Web Token (JWT). JWTs are used for securely transmitting information between parties as a JSON object. They consist of three parts: header, payload, and signature, separated by dots.
This function validates the JWT by performing the following checks: 1. The input string should consist of three parts separated by dots. 2. Each part should be a valid Base64URL encoded string.
If the input string passes these checks, the function returns true, indicating that the string is a valid JWT. Otherwise, it returns false.
Example usage:
is.JWT("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIi" +
"wibWVzc2FnZSI6IkhlbGxvIFdvcmxkIiwiaWF0IjoxNTE2MjM5MDIyfQ.pfdTXv" +
"HNIobiLJJ1MoiNyuzf5ZaUCpMu889Q8AJaWjs") // Returns: true
is.JWT("notajwt") // Returns: false
func Latitude ¶
Latitude validates if the given value is a valid geographic latitude. A latitude represents a geographic coordinate that specifies the north-south position of a point on the Earth's surface. It is an angle which ranges from -90 to +90 degrees.
The value may be a float64 or a string. A string must be a plain decimal number (an optional sign followed by digits and an optional fractional part); scientific notation, hexadecimal floats, and digit separators are rejected.
Example usage:
is.Latitude(-45.0) // Returns: true
is.Latitude("45.5") // Returns: true
is.Latitude(90.1) // Returns: false (out of range)
is.Latitude("1e1") // Returns: false (scientific notation)
is.Latitude("0x1p4") // Returns: false (hexadecimal float)
Example ¶
package main
import (
"fmt"
"github.com/goloop/is/v2"
)
func main() {
fmt.Println(is.Latitude(45.5))
fmt.Println(is.Latitude("45.5"))
fmt.Println(is.Latitude("1e1")) // scientific notation rejected
fmt.Println(is.Latitude(90.1)) // out of range
}
Output: true true false false
func Longitude ¶
Longitude validates if the given value is a valid geographic longitude. A longitude represents a geographic coordinate that specifies the east-west position of a point on the Earth's surface. It is an angle which ranges from -180 to +180 degrees.
The value may be a float64 or a string. A string must be a plain decimal number (an optional sign followed by digits and an optional fractional part); scientific notation, hexadecimal floats, and digit separators are rejected.
Example usage:
is.Longitude(-45.0) // Returns: true
is.Longitude("123.4") // Returns: true
is.Longitude(180.1) // Returns: false (out of range)
is.Longitude("1_0") // Returns: false (digit separator)
func Lower ¶
Lower checks whether a string consists only of lowercase alphabetic characters.
Example usage:
is.Lower("abc") // Output: true
is.Lower("Abc") // Output: false, contains an uppercase letter
is.Lower("abc123") // Output: false, contains a number
is.Lower("abc!") // Output: false, contains a special character
func MAC ¶
MAC checks if the string is a valid IEEE 802 MAC address. It accepts the standard textual forms parsed by the standard library: six groups of two hex digits separated by colons or hyphens (EUI-48), the four-group dotted form, and the eight-group EUI-64 variants.
Example usage:
is.MAC("00:1b:63:84:45:e6") // Returns: true
is.MAC("00-1B-63-84-45-E6") // Returns: true
is.MAC("001b.6384.45e6") // Returns: true
is.MAC("00:1b:63:84:45") // Returns: false, too few groups
is.MAC("") // Returns: false, empty string
func MD5 ¶
MD5 checks if the given string is a valid MD5 hash. MD5 is a widely used cryptographic hash function that produces a 128-bit (16-byte) hash value. It is commonly used to verify data integrity and to store passwords.
This function validates the MD5 hash by performing the following checks: 1. The input string should consist of exactly 32 characters. 2. Each character should be a valid hexadecimal digit (0-9, a-f, A-F).
Unlike Hex, this function rejects the '0x' and '#' prefixes: a real MD5 digest is exactly 32 hexadecimal nibbles with no decoration.
If the input string passes these checks, the function returns true, indicating that the string is a valid MD5 hash. Otherwise, it returns false.
Example usage:
is.MD5("d41d8cd98f00b204e9800998ecf8427e") // Returns: true
is.MD5("0xd41d8cd98f00b204e9800998ecf842") // Returns: false
is.MD5("notamd5hash") // Returns: false
Example ¶
package main
import (
"fmt"
"github.com/goloop/is/v2"
)
func main() {
fmt.Println(is.MD5("d41d8cd98f00b204e9800998ecf8427e"))
fmt.Println(is.MD5("0xd41d8cd98f00b204e9800998ecf842")) // no prefix allowed
}
Output: true false
func Natural ¶
Natural checks if the numerable value v is a natural number. A natural number is a positive integer starting from 1. Zero is not considered a natural number. The function uses generic type T, which must satisfy the Numerable type constraint.
Example usage:
is.Natural(5) // Output: true is.Natural(5.0) // Output: true is.Natural(-5) // Output: false is.Natural(0) // Output: false is.Natural(3.14) // Output: false
Please note that this function checks if the value is a whole number and is positive.
func Negative ¶
Negative verifies if the numerable value v is less than zero. The function uses generic type T, which must satisfy the Numerable type constraint. This function is useful for validating the sign of numerical data.
Example usage:
is.Negative(5) // Output: false is.Negative(-5) // Output: true is.Negative(0) // Output: false is.Negative(3.14) // Output: false is.Negative(-3.14) // Output: true
Please note that zero is neither positive nor negative. It lies between positive and negative numbers on the number line and does not change the value of another number when it is added to or subtracted from it.
func Nickname ¶
Nickname checks if the provided string is a valid nickname.
In non-strict mode (default), it allows Unicode letters, numbers, and underscores, and the length must be within 1 to 15 characters. This is useful when validating user input for account creation or profile updates in international contexts.
In strict mode, activated by passing `true` as the optional parameter, it only allows ASCII letters, numbers, and underscores, within the same length constraints.
Consistent with the package's no-cleaning principle, the input is validated as-is: surrounding whitespace is NOT trimmed, so " user" is invalid. Trim the input beforehand (e.g. with the companion 'g' package) if needed.
Example usage:
nickname := "User123"
if is.Nickname(nickname) {
fmt.Println("Nickname is valid (non-strict mode)!")
} else {
fmt.Println("Invalid nickname!")
}
if is.Nickname(nickname, true) {
fmt.Println("Nickname is valid (strict mode)!")
} else {
fmt.Println("Invalid nickname in strict mode!")
}
func Numeric ¶
Numeric checks whether a string represents a number: an optional leading '+' or '-' sign, decimal digits, and at most one decimal/grouping separator. The digits may come from any writing system whose decimal digits are classified as Unicode "Number, decimal digit" (category Nd) — e.g. ASCII, Arabic-Indic, Devanagari, Thai — so localized input validates out of the box.
What it deliberately rejects:
- letter-based numeral systems (Hebrew, Greek, Armenian, Coptic, …), whose glyphs are letters, not digits, and would otherwise let ordinary words pass as "numbers";
- ideographic and alphabetic numerals (CJK 一二三, Roman Ⅳ), which are not decimal digits;
- a string with no digit at all (a lone separator or sign such as "." or "-").
The function returns true only when every character is valid AND at least one decimal digit is present.
Example usage:
is.Numeric("1234") // Output: true
is.Numeric("3.14") // Output: true
is.Numeric("-456,789") // Output: true (comma as a separator)
is.Numeric("٣.١٤") // Output: true (Arabic-Indic digits)
is.Numeric("Ⅳ") // Output: false (Roman numeral, not a digit)
is.Numeric("一二三") // Output: false (CJK numerals, not digits)
is.Numeric("1234abc") // Output: false
is.Numeric("1.2.3") // Output: false (more than one separator)
is.Numeric(".") // Output: false (no digit)
Example ¶
package main
import (
"fmt"
"github.com/goloop/is/v2"
)
func main() {
fmt.Println(is.Numeric("3.14")) // decimal
fmt.Println(is.Numeric("٣٫١٤")) // Arabic-Indic digits
fmt.Println(is.Numeric("一二三")) // CJK numerals are not digits
fmt.Println(is.Numeric(".")) // no digit
}
Output: true true false false
func Odd ¶
Odd checks if a value is an odd number.
The function accepts a value of any type T that satisfies the Numerable interface. If the `f` argument is provided and set to true, the function ignores the fractional part of the value when checking for oddness. For integer types, it checks if the value is not divisible by 2 without a remainder. For floating-point types, it considers only the integer part of the value and determines the parity of the integer part. If the value has a non-zero fractional part and `f` is true, it returns true since an odd number cannot have a fractional part. Otherwise, it returns the negation of the IsEven function.
Example usage:
odd := is.Odd(7) fmt.Println(odd) // Output: true even := is.Odd(6) fmt.Println(even) // Output: false floatingPoint := is.Odd(7.7) fmt.Println(floatingPoint) // Output: false floatingPoint = is.Odd(7.7, true) fmt.Println(floatingPoint) // Output: true
func Phone ¶
Phone checks if the given string is a valid phone number. The phone number can have the following format: - It starts with a plus sign (+) followed by the country code. - The country code can be enclosed in parentheses. - Digits may be separated by spaces, hyphens, or dots.
These common grouping separators are ignored before validation; once they are removed, the remaining value must be a '+' followed by 1 to 15 digits (the E.164 maximum).
Example usage:
is.Phone("+380 (96) 00 00 000") // Returns: true
is.Phone("+1-234-567-8900") // Returns: true
is.Phone("+380961234567") // Returns: true
is.Phone("123456789") // Returns: false, no plus sign
is.Phone("+1234567890123456") // Returns: false, more than 15 digits
is.Phone("") // Returns: false, empty string
This function can be used to validate user input or data to ensure it follows the specified format for phone numbers.
func Positive ¶
Positive verifies if the numerable value v is greater than zero. The function uses generic type T, which must satisfy the Numerable type constraint. This function is useful for validating the sign of numerical data.
Example usage:
is.Positive(5) // Output: true is.Positive(-5) // Output: false is.Positive(0) // Output: false is.Positive(3.14) // Output: true is.Positive(-3.14) // Output: false
Please note that zero is neither positive nor negative. It lies between positive and negative numbers on the number line and does not change the value of another number when it is added to or subtracted from it.
func RGBColor ¶
RGBColor validates whether a given string 'v' is a valid RGB color value. RGB color values are defined as 'rgb(<red>, <green>, <blue>)', where each of <red>, <green>, and <blue> is an integer in the range 0-255. The function uses a regular expression to verify that the input string conforms to this format.
The function does not account for leading or trailing spaces in the input string. The values for red, green, and blue must be separated by commas. These can be followed by spaces, tabs, or newline characters, all of which are considered valid. The entire string must be enclosed within 'rgb()' with no spaces between 'rgb' and the opening parenthesis.
If the input string matches this format and all color values are in the range 0-255, the function returns true, indicating that the string is a valid RGB color value. Otherwise, it returns false.
Example usage:
is.RGBColor("rgb(255, 255, 255)") // Returns: true
is.RGBColor("rgb(255, 255, 256)") // Returns: false
is.RGBColor("rgb(255, 255)") // Returns: false
Note: The function doesn't validate color semantic correctness, just the syntax and range of values.
func SHA1 ¶
SHA1 checks if the given string is a valid SHA-1 hash: exactly 40 hexadecimal digits (0-9, a-f, A-F) with no '0x'/'#' prefix. It validates the format only, not the cryptographic provenance of the value.
Example usage:
is.SHA1("da39a3ee5e6b4b0d3255bfef95601890afd80709") // Returns: true
is.SHA1("da39a3ee") // Returns: false
func SHA256 ¶
SHA256 checks if the given string is a valid SHA-256 hash: exactly 64 hexadecimal digits (0-9, a-f, A-F) with no '0x'/'#' prefix. It validates the format only, not the cryptographic provenance of the value.
Example usage:
is.SHA256("e3b0c44298fc1c149afbf4c8996fb924" +
"27ae41e4649b934ca495991b7852b855") // Returns: true
func SHA512 ¶
SHA512 checks if the given string is a valid SHA-512 hash: exactly 128 hexadecimal digits (0-9, a-f, A-F) with no '0x'/'#' prefix. It validates the format only, not the cryptographic provenance of the value.
Example usage:
is.SHA512(strings.Repeat("0", 128)) // Returns: true
func SelectorName ¶
SelectorName checks if the given string is a valid CSS/HTML selector name. It supports simple selectors including elements (e.g., "div"), classes (e.g., ".myClass"), and IDs (e.g., "#myID").
Parameters:
- v: string to validate;
- strict: if true, the leading characters # and . are inadmissible.
Returns true if the given name is a valid selector.
func Space ¶
Space checks whether a string consists only of whitespace characters. Whitespace characters includes spaces, tabs, newlines, and other Unicode whitespace characters.
Example usage:
is.Space(" \t\n") // Output: true
is.Space("Hello") // Output: false
is.Space(" ") // Output: true
is.Space("\n\t ") // Output: true
is.Space("") // Output: false, an empty string has no characters
func Title ¶
Title checks whether a string is a titlecased string: every word starts with an upper- (or title-) case letter and continues with lowercase letters.
Word boundaries are any non-letter runes. This includes spaces and digits, but also punctuation such as the hyphen and the apostrophe, so a name like "O'Brien" is treated as the two words "O" and "Brien" (both titlecased, hence valid), and "Mc-donald" splits into "Mc" and "donald" (the second is lowercase, hence invalid). Pre-normalize the input if you need a different word model.
Example usage:
is.Title("Hello World") // Output: true
is.Title("Hello world") // Output: false, 'world' starts with a lowercase
is.Title("HELLO WORLD") // Output: false, all letters are uppercase
is.Title("hELLO wORLD") // Output: false, words start with a lowercase
is.Title("O'Brien") // Output: true, "O" and "Brien" are separate
func TokenOctet ¶ added in v2.3.1
TokenOctet reports whether b is a valid HTTP token character ("tchar").
The HTTP token grammar (RFC 9110, section 5.6.2) allows the ASCII letters and digits plus a fixed set of symbols, and nothing else:
tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" / "+" / "-" / "." /
"^" / "_" / "`" / "|" / "~" / DIGIT / ALPHA
These are the octets that may appear, unescaped, in HTTP field names, request-method names, cache-directive names and similar bare tokens. The delimiters - space, tab, control bytes and the separators ()<>@,;:\"/[]?={} - are not token characters, so TokenOctet returns false for them, and for every non-ASCII byte (0x80-0xFF).
func URL ¶
URL checks if the string is a valid absolute URL: it must have both a scheme (such as "http" or "https") and a host. Relative references and scheme-only or host-less inputs are rejected.
The function validates structure, not reachability: it does not perform any network request.
Example usage:
is.URL("https://example.com") // Returns: true
is.URL("http://example.com:8080/path") // Returns: true
is.URL("ftp://files.example.com") // Returns: true
is.URL("example.com") // Returns: false, no scheme
is.URL("/relative/path") // Returns: false, no scheme/host
is.URL("https://") // Returns: false, no host
is.URL("") // Returns: false, empty string
Example ¶
package main
import (
"fmt"
"github.com/goloop/is/v2"
)
func main() {
fmt.Println(is.URL("https://example.com"))
fmt.Println(is.URL("example.com")) // no scheme
}
Output: true false
func UUID ¶
UUID checks if the given string is a valid UUID in the canonical 8-4-4-4-12 hexadecimal form (36 characters with hyphens), for example "550e8400-e29b-41d4-a716-446655440000".
It validates the textual format only and accepts any version/variant; it does not require the version or variant nibbles to take particular values, and it does not accept braces, URN prefixes, or the unhyphenated form.
Example usage:
is.UUID("550e8400-e29b-41d4-a716-446655440000") // Returns: true
is.UUID("550E8400-E29B-41D4-A716-446655440000") // Returns: true
is.UUID("550e8400e29b41d4a716446655440000") // Returns: false
is.UUID("not-a-uuid") // Returns: false
Example ¶
package main
import (
"fmt"
"github.com/goloop/is/v2"
)
func main() {
fmt.Println(is.UUID("550e8400-e29b-41d4-a716-446655440000"))
fmt.Println(is.UUID("550e8400e29b41d4a716446655440000")) // needs hyphens
}
Output: true false
func Upper ¶
Upper checks whether a string consists only of uppercase alphabetic characters.
Example usage:
is.Upper("ABC") // Output: true
is.Upper("AbC") // Output: false, contains a lowercase letter
is.Upper("ABC123") // Output: false, contains a number
is.Upper("ABC!") // Output: false, contains a special character
func VariableName ¶
VariableName validates if the given string can be used as a variable name without considering specific programming language.
Parameters:
- v: string to validate
- strict: if true, checks if the word is reserved in any programming language.
Returns true if the given name is valid.
func VariableNameFor ¶
VariableNameFor validates if the given string can be used as a variable name in the specified programming language.
Parameters:
- v: string to validate;
- language: programming language to check against (case-insensitive);
Returns:
- bool: true if the given name is valid for the specified language;
- error: ErrLanguageNotSupported if the language is not supported.
Example ¶
package main
import (
"errors"
"fmt"
"github.com/goloop/is/v2"
)
func main() {
ok, _ := is.VariableNameFor("myVar", "go")
fmt.Println(ok)
// csharp is now fully supported (previously this call panicked).
ok, _ = is.VariableNameFor("myVar", "csharp")
fmt.Println(ok)
_, err := is.VariableNameFor("x", "klingon")
fmt.Println(err)
fmt.Println(errors.Is(err, is.ErrLanguageNotSupported))
}
Output: true true programming language is not supported: "klingon" true
func Whole ¶
Whole checks if a value is a whole number.
The function accepts a value of any type T that satisfies the Numerable interface. It first checks if the value has a non-zero fractional part. If it does, it returns false since a whole number cannot have a fractional part. If the value does not have a fractional part, it returns true.
Example usage:
whole := is.Whole(5) fmt.Println(whole) // Output: true notWhole := is.Whole(5.5) fmt.Println(notWhole) // Output: false zero := is.Whole(0) fmt.Println(zero) // Output: true negative := is.Whole(-3) fmt.Println(negative) // Output: true
func Zero ¶
Zero checks if the numerable value v is equal to zero. The function uses generic type T, which must satisfy the Numerable type constraint. This function is useful for validating whether the numerical data equals zero.
Example usage:
is.Zero(5) // Output: false is.Zero(-5) // Output: false is.Zero(0) // Output: true is.Zero(3.14) // Output: false is.Zero(-3.14) // Output: false
Please note that zero is a unique number that is neither positive nor negative. It lies between positive and negative numbers on the number line and does not change the value of another number when it is added to or subtracted from it.
Types ¶
type CardKind ¶
type CardKind int
CardKind identifies a bank card brand accepted by BankCard.
In contrast to exporting the underlying regular expressions, an opaque kind keeps the matching patterns immutable: callers select a brand by constant and cannot replace a global regex and silently break validation for the whole process.
The zero value is not a valid kind. Use the exported constants below.
const ( // Visa matches Visa cards. Visa CardKind = iota + 1 // MasterCard matches MasterCard cards. MasterCard // AmericanExpress matches American Express cards. AmericanExpress // DiscoverCard matches Discover cards. DiscoverCard // DCI matches Diners Club International cards. DCI // UnionPay matches UnionPay cards. UnionPay // JCB matches JCB cards. JCB // Argencard matches Argencard cards. Argencard // Cabal matches Cabal cards. Cabal // Cencosud matches Cencosud cards. Cencosud // ChinaUnionPay matches China UnionPay cards. ChinaUnionPay // DinersClubCarteBlanche matches Diners Club Carte Blanche cards. DinersClubCarteBlanche // DinersClubInternational matches Diners Club International cards. DinersClubInternational // DinersClubUSAndCanada matches Diners Club US & Canada cards. DinersClubUSAndCanada // DinersClub matches Diners Club cards. DinersClub // InstaPayment matches InstaPayment cards. InstaPayment // Laser matches Laser cards. Laser // Maestro matches Maestro cards. Maestro // VisaElectron matches Visa Electron cards. VisaElectron // Dankort matches Dankort cards. Dankort // RuPay matches RuPay cards. RuPay // InterPayment matches InterPayment cards. InterPayment // Troy matches Troy cards. Troy // MIR matches MIR cards. MIR // UATP matches UATP cards. UATP // Hipercard matches Hipercard cards. Hipercard // Naranja matches Naranja cards. Naranja // TarjetaShopping matches Tarjeta Shopping cards. TarjetaShopping // ELO matches Elo cards. ELO )
type Numerable ¶
Numerable is an interface type that is satisfied by all numeric types in Go, both integer and floating point. This includes int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64, float32, and float64. It allows functions to operate on any of these types where numerical operations such as addition, subtraction, multiplication, and division are needed. It enables generic programming techniques for numeric types.
type Verifiable ¶
type Verifiable interface {
g.Verifiable
}
Verifiable is an interface type that is satisfied by classical types like numeric types and strings in Go.
The purpose of the Verifiable interface is to enable generic programming techniques for numeric types and strings. Functions can use this interface as a constraint to operate on any of these types where numerical operations or string operations are needed.