is

package module
v1.5.5 Latest Latest
Warning

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

Go to latest
Published: Dec 1, 2024 License: MIT Imports: 9 Imported by: 1

README

Go Report Card License License Stay with Ukraine

is

The is package provides a comprehensive set of validation functions for various data types commonly used in web applications, financial systems, and general software development. It offers a clean, efficient way to validate data formats ranging from basic types to complex financial and network identifiers.

Features

Account & Identity Validation
  • Email(string) bool - Email addresses
  • Nickname(string, ...bool) bool - Usernames (with optional strict mode)
  • VariableName(string, ...bool) bool - Programming variable names
  • VariableNameFor(string, string) (bool, error) - Language-specific variable names
Financial Validation
  • BankCard(string, ...*regexp.Regexp) bool - Credit/Debit card numbers with optional card type checking
  • IBAN(string, ...bool) bool - International Bank Account Numbers
  • Iban(string, ...bool) bool - Alias for IBAN validation
Geographic Validation
  • Latitude[T string|float64](T) bool - Latitude coordinates
  • Longitude[T string|float64](T) bool - Longitude coordinates
  • Coordinates[T string|float64](lat, lon T) bool - Coordinate pairs
Network & Communication
  • IPv4(string) bool - IPv4 addresses
  • IPv6(string) bool - IPv6 addresses
  • IP(string) bool - Any IP address (v4 or v6)
  • Phone(string) bool - Phone numbers
  • E164(string) bool - E.164 format phone numbers
String Type Validation
  • Alpha(string) bool - Alphabetic characters
  • Alnum(string) bool - Alphanumeric characters
  • Digit(string) bool - Numeric digits only
  • Lower(string) bool - Lowercase letters
  • Upper(string) bool - Uppercase letters
  • Title(string) bool - Title case text
  • Space(string) bool - Whitespace characters
  • Numeric(string) bool - Numeric strings (including decimals)
  • Decimal(string) bool - Decimal numbers
  • Float(string) bool - Floating-point numbers
Number Type Validation
  • Even[T Numerable](T, ...bool) bool - Even numbers
  • Odd[T Numerable](T, ...bool) bool - Odd numbers
  • Whole[T Numerable](T) bool - Whole numbers
  • Natural[T Numerable](T) bool - Natural numbers
  • Positive[T Numerable](T) bool - Positive numbers
  • Negative[T Numerable](T) bool - Negative numbers
  • Zero[T Numerable](T) bool - Zero value check
Encoding & Format Validation
  • Base64(string) bool - Base64 encoding
  • Base64URL(string) bool - URL-safe Base64 encoding
  • Hex(string) bool - Hexadecimal strings
  • Bin(string) bool - Binary strings
  • HexColor(string) bool - Hexadecimal color codes
  • RGBColor(string) bool - RGB color format
  • MD5(string) bool - MD5 hash strings
  • JWT(string) bool - JSON Web Tokens
Mobile & Telecom
  • IMEI[T string|int64](T) bool - International Mobile Equipment Identity
  • IMSI(string) bool - International Mobile Subscriber Identity

Installation

go get -u github.com/goloop/is

Important Note

The package provides validation functions that do not pre-clean the data. If the validation data needs to be cleaned, it must be cleaned beforehand, for example, using the g package.

Example:

raw := "GB82 WEST 1234 5698 7654 32"    // contains spaces
iban := g.Weed(raw, g.Whitespaces)      // remove spaces
valid := is.IBAN(iban)                  // validate

Usage Examples

Basic Validation
package main

import (
    "fmt"
    "github.com/goloop/is"
)

func main() {
    // Email validation.
    fmt.Println(is.Email("user@example.com"))         // true
    fmt.Println(is.Email("invalid-email"))            // false

    // Phone number validation.
    fmt.Println(is.Phone("+1 (234) 567-8900"))        // true
    fmt.Println(is.E164("+12345678900"))              // true

    // Geographic coordinates.
    fmt.Println(is.Coordinates(51.5074, -0.1278))     // true
    fmt.Println(is.Coordinates(91.0, 0.0))            // false

    // Financial validation.
    fmt.Println(is.BankCard("4111111111111111"))      // true
    fmt.Println(is.IBAN("DE89370400440532013000"))    // true
}
Advanced Validation
package main

import (
    "fmt"
    "github.com/goloop/is"
)

func main() {
    // Variable name validation for different languages.
    fmt.Println(is.VariableNameFor("myVar", "go"))     // true
    fmt.Println(is.VariableNameFor("class", "python")) // false (reserved word)

    // Strict mode validation.
    fmt.Println(is.Nickname("user123", true))          // true
    fmt.Println(is.Nickname("user@123", true))         // false

    // Number validation.
    fmt.Println(is.Even(4))                            // true
    fmt.Println(is.Natural(5))                         // true
    fmt.Println(is.Positive(-1))                       // false

    // Format validation.
    fmt.Println(is.HexColor("#FF5733"))                // true
    fmt.Println(is.Base64("SGVsbG8="))                 // true
    fmt.Println(is.JWT("eyJhbGciOiJIUzI..."))          // true
}

Contributing

Contributions are welcome! Here are a few ways you can help:

  1. Report bugs by opening an issue
  2. Suggest new features or improvements
  3. Submit pull requests
  4. Improve documentation
  5. Share the package with others

Please make sure to:

  • Write tests for new features
  • Follow Go coding standards
  • Update documentation as needed
  • Add comments to explain complex logic

License

This project is licensed under the MIT License - see the LICENSE file for details.

Credits

Created and maintained by Goloop Team

  • g - Go utility functions package

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;
  • Telecommunications: phone numbers in E.164 format;
  • String Types: alphanumeric, numeric, hexadecimal, binary;
  • Numbers: even/odd, positive/negative, natural numbers;
  • Encodings: Base64, Base64URL, JWT tokens;
  • Data formats: MD5 hashes.

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

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.JWT("eyJhbGciOiJIUzI...")     // JWT token

For more detailed information about specific validation functions, see their respective documentation.

Index

Constants

This section is empty.

Variables

View Source
var (

	// Visa is a regular expression for matching Visa bank card.
	Visa = regexp.MustCompile(`^4[0-9]{12}(?:[0-9]{3})?$`)

	// MasterCard is a regular expression for matching MasterCard bank card.
	MasterCard = regexp.MustCompile(`^5[1-5][0-9]{14}$`)

	// AmericanExpress is a regular expression for matching
	// American Express bank card.
	AmericanExpress = regexp.MustCompile(`^3[47][0-9]{13}$`)

	// DiscoverCard is a regular expression for matching
	// Discover Card bank card.
	DiscoverCard = regexp.MustCompile(`^6(?:011\d{12}|5\d{14}|4[4-9]\d{13}|22(?:1(?:2[6-9]|[3-9]\d)|[2-8]\d{2}|9(?:[01]\d|2[0-5]))\d{10})$`)

	// DCI is a regular expression for matching DCI bank card.
	DCI = regexp.MustCompile(`^3(?:0[0-5]|[68][0-9])[0-9]{11}$`)

	// UnionPay is a regular expression for matching UnionPay bank card.
	UnionPay = regexp.MustCompile("^62[0-5]\\d{13,16}$")

	// JCB is a regular expression for matching JCB bank card.
	JCB = regexp.MustCompile(`^(?:2131|1800|35[0-9]{3})[0-9]{11}$`)

	// Argencard is a regular expression for matching Argencard bank card.
	Argencard = regexp.MustCompile(`^501105\d{10}$`)

	// Cabal is a regular expression for matching Cabal bank card.
	Cabal = regexp.MustCompile(`^6042(0[1-9]|10|1[1-9])\d{6}$`)

	// Cencosud is a regular expression for matching Cencosud bank card.
	Cencosud = regexp.MustCompile(`^603493\d{10}$`)

	// ChinaUnionPay is a regular expression for matching
	// China UnionPay bank card.
	ChinaUnionPay = regexp.MustCompile(`^62[0-9]{14,17}$`)

	// DinersClubCarteBlanche is a regular expression for matching
	// Diners Club Carte Blanche bank card.
	DinersClubCarteBlanche = regexp.MustCompile(`^30[0-5][0-9]{11}$`)

	// DinersClubInternational is a regular expression for matching
	// Diners Club International bank card.
	DinersClubInternational = regexp.MustCompile(`^36[0-9]{12}$`)

	// DinersClubUSAndCanada is a regular expression for matching
	// Diners Club US & Canada bank card.
	DinersClubUSAndCanada = regexp.MustCompile(`^5[45][0-9]{14}$`)

	// DinersClub is a regular expression for matching Diners Club bank card.
	DinersClub = regexp.MustCompile(`^3(?:0[0-5]|[68][0-9])[0-9]{11}$`)

	// InstaPayment is a regular expression for matching
	// InstaPayment bank card.
	InstaPayment = regexp.MustCompile(`^63[7-9][0-9]{13}$`)

	// Laser is a regular expression for matching Laser bank card.
	Laser = regexp.MustCompile(`^(6304|670[69]|6771)[0-9]{12,15}$`)

	// Maestro is a regular expression for matching Maestro bank card.
	Maestro = regexp.MustCompile(`^(5018|5020|5038|6304|6759|676[1-3])[0-9]{8,15}$`)

	// VisaElectron is a regular expression for matching
	// Visa Electron bank card.
	VisaElectron = regexp.MustCompile(`^(4026|417500|4508|4844|491[37])[0-9]{12}$`)

	// Dankort is a regular expression for matching Dankort bank card.
	Dankort = regexp.MustCompile(`^(5019)[0-9]{12}$`)

	// RuPay is a regular expression for matching RuPay bank card.
	RuPay = regexp.MustCompile(`^(508[5-9][0-9]{1}|60698|60699|607[0-8][0-9]{1}|6079[0-7]|60798[0-4]|608[0-4][0-9]{1}|608500)[0-9]{6,9}$`)

	// InterPayment is a regular expression for matching
	// InterPayment bank card.
	InterPayment = regexp.MustCompile(`^636[0-9]{12,15}$`)

	// Troy is a regular expression for matching Troy bank card.
	Troy = regexp.MustCompile(`^9792[0-9]{12}$`)

	// MIR is a regular expression for matching MIR bank card.
	MIR = regexp.MustCompile(`^220[0-9]{13}$`)

	// UATP is a regular expression for matching UATP bank card.
	UATP = regexp.MustCompile(`^1[0-9]{14}$`)

	// Hipercard is a regular expression for matching Hipercard bank card.
	Hipercard = regexp.MustCompile(`^(606282\d{10}(\d{3})?)|(3841\d{02}\d{10})$`)

	// Naranja is a regular expression for matching Naranja bank card.
	Naranja = regexp.MustCompile(`^589562\d{10}$`)

	// TarjetaShopping is a regular expression for matching
	// Tarjeta Shopping bank card.
	TarjetaShopping = regexp.MustCompile(`^603488\d{10}$`)

	// ELO is a regular expression for matching ELO bank card.
	ELO = regexp.MustCompile(`^(401178|401179|431274|438935|451416|457393|457631|457632|504175|627780|636297|636368|636369)\d{10}$`)
)
View Source
var (

	// ErrLanguageNotSupported indicates that the specified
	// programming language is not supported.
	ErrLanguageNotSupported = func(lang string) error {
		return fmt.Errorf("programming language '%s' is not supported", lang)
	}
)

Functions

func Alnum

func Alnum(s string) bool

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: false

func Alpha

func Alpha(s string) bool

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: false, contains a non-Latin letter

func BankCard

func BankCard(str string, kinds ...*regexp.Regexp) bool

BankCard validates a bank card number based on provided card types. If no type is given, it checks against any type.

BankCard uses Luhn algorithm to validate the card number and tests as Credit Card and Debit Card.

Example usage:

is.BankCard("4111111111111111")
// Output: true
// As it's a valid card number, checked against any type.

is.BankCard("4111111111111111", is.MasterCard)
// Output: false
// It's a valid card but not of type MasterCard.

is.BankCard("4111111111111111", is.Visa)
// Output: true
// It's a valid Visa card.

is.BankCard("4111111111111111", is.Visa, is.MasterCard)
// Output: true
// It's a valid card of either Visa or MasterCard type.

is.BankCard("1234567812345678")
// Output: false
// Not a valid card number.

func Base64 added in v0.7.2

func Base64(v string) bool

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

func Base64URL(v string) bool

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

func Bin(v string) bool

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

func CalculateIBANChecksum(iban string) *big.Int

CalculateIBANChecksum calculates the checksum of an IBAN as per the specifications. This is used to verify the validity of an IBAN number.

func Coordinates added in v1.0.0

func Coordinates[T string | float64](lat, lon T) bool

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 float64 numbers 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

func Decimal(s string) bool

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

func Digit(s string) bool

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

func E164(v string) bool

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: true
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

func Email(email string) bool

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

func Even

func Even[T Numerable](v T, f ...bool) bool

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

func Float(s string) bool

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

func Hex(v string) bool

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

func HexColor(v string) bool

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 IBAN

func IBAN(iban string, strict ...bool) bool

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.

func IMEI added in v1.0.0

func IMEI[T string | int64](imei T) bool

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

func IMSI(imsi string) bool

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 by performing the following checks: 1. The length of the IMSI should be 15 digits. 2. The first three digits (MCC) should be a valid MCC. 3. The following two or three digits (MNC) should be a valid MNC. 4. The remaining digits (MSIN) should be numeric.

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

func IP added in v1.0.0

func IP(ip string) bool

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

func IPv4(ip string) bool

IPv4 checks if the string is a valid representation of an IPv4 address. An IPv4 address consists of four numbers separated by dots. Each number should be within the range of 0 to 255. Leading zeros are allowed. Empty strings or strings with more than four parts are not considered as 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("256.0.0.1")     // Returns: false, numbers exceed the range
is.IPv4("192.168.0")     // Returns: false, only three parts
is.IPv4("192.168.0.1.1") // Returns: false, more than four parts
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.

func IPv6 added in v1.0.0

func IPv6(ip string) bool

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 the net.ParseIP function from the Go standard library which returns a valid IP address (either IPv6 or IPv4). The function then checks if the string contains a colon, which is a requirement for it to be an IPv6 address.

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

func Iban(iban string, strict ...bool) bool

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 JWT added in v1.1.0

func JWT(v string) bool

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

func Latitude[T string | float64](lat T) bool

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 function takes a float64 number representing the latitude and checks if it falls within the valid range.

Example usage:

is.Latitude(-45.0) // Returns: true
is.Latitude(90.1)  // Returns: false

func Longitude added in v1.0.0

func Longitude[T string | float64](lon T) bool

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 function takes a float64 number representing the longitude and checks if it falls within the valid range.

Example usage:

is.Longitude(-45.0) // Returns: true
is.Longitude(180.1) // Returns: false

func Lower

func Lower(s string) bool

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 MD5 added in v1.1.0

func MD5(v string) bool

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

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("notamd5hash") // Returns: false

func Natural

func Natural[T Numerable](v T) bool

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

func Negative[T Numerable](v T) bool

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

func Nickname(nickname string, strict ...bool) bool

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.

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

func Numeric(s string) bool

Numeric checks whether a string consists only of numeric characters, including digits, decimal separators, and an optional '+' or '-' sign at the beginning. The function recognizes integers and floating-point numbers, as well as digits from various numeral systems and scripts.

Returns true if all characters in the string are numeric, and false otherwise. The function supports decimal separators from different cultures.

Example usage:

is.Numeric("1234")     // Output: true
is.Numeric("3.14")     // Output: true
is.Numeric("-456,789") // Output: true (if comma is considered a separator)
is.Numeric("Ⅳ")       // Output: true
is.Numeric("三・十四")  // Output: true
is.Numeric("1234abc")  // Output: false
is.Numeric("1.2.3")    // Output: false (more than one decimal separator)

func Odd

func Odd[T Numerable](v T, f ...bool) bool

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

func Phone(phone string) bool

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. - The phone number can contain spaces between digits.

Example usage:

is.Phone("+380 (96) 00 00 000") // Returns: true
is.Phone("+380961234567")       // Returns: true
is.Phone("123456789")           // Returns: false, no plus sign
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

func Positive[T Numerable](v T) bool

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

func RGBColor(v string) bool

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 Sel added in v1.4.0

func Sel(v string, strict ...bool) bool

Sel is synonym for SelectorName function.

func SelectorName added in v1.4.0

func SelectorName(v string, strict ...bool) bool

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

func Space(s string) bool

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

func Title(s string) bool

Title checks whether a string is a titlecased string.

In a titlecased string, upper- and title-case characters may only follow uncased characters and lowercase characters only cased ones.

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

func Upper

func Upper(s string) bool

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 Var added in v1.2.0

func Var(v string, strict ...bool) bool

Var is synonym for VariableName function.

func VarFor added in v1.5.0

func VarFor(v string, language string) (bool, error)

VarFor is synonym for VariableNameFor function.

func VariableName added in v1.4.0

func VariableName(v string, strict ...bool) bool

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

func VariableNameFor(v string, language string) (bool, error)

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.

func Whole

func Whole[T Numerable](v T) bool

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

func Zero[T Numerable](v T) bool

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 Numerable

type Numerable interface {
	g.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.

Jump to

Keyboard shortcuts

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