Skip to main content

is - Data Validation Utility Library

is is a comprehensive data validation and type checking utility library that provides a large number of simple and easy-to-use validation functions, covering common data types and format validation needs.

Installation

go get -u go-slim.dev/is

Quick Start

package main

import (
"fmt"
"go-slim.dev/is"
)

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

// Phone number validation (China)
fmt.Println(is.PhoneNumber("13800138000")) // true

// UUID validation
fmt.Println(is.UUID("550e8400-e29b-41d4-a716-446655440000")) // true

// Range validation
fmt.Println(is.Between(25, 18, 65)) // true

// IP address validation
fmt.Println(is.IPv4("192.168.1.1")) // true

// URL validation
fmt.Println(is.URL("https://example.com")) // true
}

Core Function Categories

1. String Format Validation

Email - Email Validation

func Email(str string) bool

Description: Validates whether a string is a valid email address, supports internationalized emails, and complies with RFC 5322 standards.

Examples:

is.Email("user@example.com")      // true
is.Email("user+tag@domain.org") // true
is.Email("用户@example.cn") // true (supports internationalization)
is.Email("invalid-email") // false
is.Email("@example.com") // false (missing username)

PhoneNumber - Phone Number Validation (China)

func PhoneNumber(s string) bool

Description: Validates whether a string is a valid Chinese mobile phone number, supports domestic format and international format (+86 prefix).

Examples:

is.PhoneNumber("13800138000")      // true
is.PhoneNumber("+8613800138000") // true
is.PhoneNumber("12345678901") // false (invalid format)
is.PhoneNumber("28001380000") // false (invalid prefix)

Idcard - ID Card Number Validation (China)

func Idcard(s string) bool

Description: Validates whether a string is a valid Chinese ID card number. Supports 15-digit and 18-digit formats.

Examples:

is.Idcard("11010519491231002X")    // true (18-digit with X check digit)
is.Idcard("110105491231002") // true (15-digit format)
is.Idcard("110105194912310021") // true (18-digit numeric check digit)
is.Idcard("123456789012345") // false (invalid format)

URL - URL Validation

func URL(s string) bool

Description: Validates whether a string is a valid URL. Supports multiple protocols (http, https, ftp, etc.).

Examples:

is.URL("https://example.com")        // true
is.URL("ftp://user:pass@host/path") // true
is.URL("http://localhost:8080") // true
is.URL("example.com") // false (missing protocol)
is.URL("") // false (empty string)

2. Unique Identifier Validation

UUID - Universally Unique Identifier

func UUID(str string) bool    // Any version
func UUID3(str string) bool // UUID v3 (MD5 hash)
func UUID4(str string) bool // UUID v4 (random)
func UUID5(str string) bool // UUID v5 (SHA-1 hash)

Description: Validates UUID format. UUID is a 128-bit unique identifier, typically displayed as 32 hexadecimal digits separated by hyphens (8-4-4-4-12).

Examples:

// UUID v4 (most common)
is.UUID4("550e8400-e29b-41d4-a716-446655440000") // true
is.UUID4("6ba7b810-9dad-11d1-80b4-00c04fd430c8") // false (v3)

// UUID v3
is.UUID3("6ba7b810-9dad-11d1-80b4-00c04fd430c8") // true

// UUID v5
is.UUID5("6ba7b810-9dad-11d1-80b4-00c04fd430c8") // true

// Any version
is.UUID("550e8400-e29b-41d4-a716-446655440000") // true
is.UUID("not-a-uuid") // false

ULID - Sortable Unique Identifier

func ULID(str string) bool

Description: Validates whether it's a valid ULID (Universally Unique Lexicographically Sortable Identifier). ULID is a 26-character string, sortable by time.

Examples:

is.ULID("01ARZ3NDEKTSV4RRFFQ69G5FAV")  // true
is.ULID("01BX5ZZKBKACTAV9WEVGEMMVR0") // true
is.ULID("invalid-ulid") // false

3. Hash Value Validation

func MD4(str string) bool      // MD4 hash (32 characters)
func MD5(str string) bool // MD5 hash (32 characters)
func SHA256(str string) bool // SHA-256 hash (64 characters)
func SHA384(str string) bool // SHA-384 hash (96 characters)
func SHA512(str string) bool // SHA-512 hash (128 characters)

Description: Validates various hash digest formats.

Examples:

// MD5
is.MD5("5d41402abc4b2a76b9719d911017c592") // true ("hello")
is.MD5("invalid-hash") // false

// SHA-256
is.SHA256("2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824") // true ("hello")

// SHA-512
is.SHA512("9b71d224bd62f3785d96d46ad3ea3d73319bfbc2890caadae2dff72519673ca72323c3d99ba5c11d7c7acc6e14b8c5da0c4663475c2e5c3adef46f73bcdec043") // true ("hello")

4. Encoding Validation

Base64 - Base64 Encoding

func Base64(s string) bool
func Base64URL(str string) bool // URL-safe Base64

Examples:

// Standard Base64
is.Base64("SGVsbG8gV29ybGQ=") // true ("Hello World")
is.Base64("Hello World") // false (not encoded)

// URL-safe Base64
is.Base64URL("SGVsbG8gV29ybGQ") // true
is.Base64URL("eyJhbGciOiJIUzI1NiIs") // true (JWT header)

JWT - JSON Web Token

func JWT(str string) bool

Description: Validates JWT format. JWT consists of three parts separated by dots: header.payload.signature

Examples:

is.JWT("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4ifQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c")  // true
is.JWT("invalid.jwt") // false

URLEncoded / HTMLEncoded

func URLEncoded(str string) bool
func HTMLEncoded(str string) bool

Examples:

// URL encoding
is.URLEncoded("Hello%20World") // true
is.URLEncoded("name%3Dvalue") // true
is.URLEncoded("Hello World") // false

// HTML entity encoding
is.HTMLEncoded("Hello&World") // true
is.HTMLEncoded("<div>") // true
is.HTMLEncoded("Hello & World") // false

5. Character Type Validation

ASCII / Alpha / Alphanumeric

func ASCII(str string) bool
func Alpha(str string) bool
func Alphanumeric(str string) bool
func AlphaUnicode(str string) bool
func AlphanumericUnicode(str string) bool

Examples:

// ASCII characters
is.ASCII("Hello World") // true
is.ASCII("Héllo") // false (contains non-ASCII character)

// Letters only
is.Alpha("Hello") // true
is.Alpha("Hello123") // false (contains digits)

// Letters + digits
is.Alphanumeric("Hello123") // true
is.Alphanumeric("Hello-123") // false (contains hyphen)

// Unicode letters
is.AlphaUnicode("Héllo") // true
is.AlphaUnicode("你好") // true
is.AlphaUnicode("Привет") // true (Russian)

// Unicode letters + digits
is.AlphanumericUnicode("Café123") // true
is.AlphanumericUnicode("你好123") // true

Numeric / Number / Hexadecimal

func Numeric[T any](t T) bool
func Number[T any](t T) bool
func Hexadecimal(str string) bool

Examples:

// Numeric type (including negative, decimal)
is.Numeric(123) // true
is.Numeric(-45.67) // true
is.Numeric("123") // true
is.Numeric("abc") // false

// Pure number (integer)
is.Number(123) // true
is.Number("123") // true
is.Number(-45) // false (negative)
is.Number("12.34") // false (decimal)

// Hexadecimal
is.Hexadecimal("FF00AA") // true
is.Hexadecimal("123abc") // true
is.Hexadecimal("FFGG") // false (G is not hexadecimal)

Lowercase / Uppercase

func Lowercase(str string) bool
func Uppercase(str string) bool

Examples:

// Lowercase
is.Lowercase("hello world") // true
is.Lowercase("Hello World") // false

// Uppercase
is.Uppercase("HELLO WORLD") // true
is.Uppercase("Hello World") // false

6. Color Validation

func HEXColor(str string) bool
func RGB(str string) bool
func RGBA(str string) bool
func HSL(str string) bool
func HSLA(str string) bool
func Color(str string) bool // Supports all color formats

Examples:

// HEX color
is.HEXColor("#FF0000") // true (red)
is.HEXColor("#F00") // true (short format)
is.HEXColor("#FF000080") // true (with transparency)

// RGB
is.RGB("rgb(255, 0, 0)") // true (red)
is.RGB("rgb(255,255,255)") // true (white)

// RGBA
is.RGBA("rgba(255, 0, 0, 0.5)") // true (semi-transparent red)

// HSL
is.HSL("hsl(0, 100%, 50%)") // true (red)

// HSLA
is.HSLA("hsla(0, 100%, 50%, 0.5)") // true (semi-transparent red)

// Universal color validation
is.Color("#FF0000") // true
is.Color("rgb(255, 0, 0)") // true
is.Color("hsl(0, 100%, 50%)") // true

7. Geographic Coordinate Validation

func Latitude[T any](t T) bool
func Longitude[T any](t T) bool

Description:

  • Latitude range: -90° to +90°
  • Longitude range: -180° to +180°

Examples:

// Latitude
is.Latitude(45.0) // true
is.Latitude(-90.0) // true (South Pole)
is.Latitude("90.0") // true (North Pole)
is.Latitude(91.0) // false (out of range)

// Longitude
is.Longitude(120.0) // true
is.Longitude(-180.0) // true
is.Longitude("180.0") // true
is.Longitude(181.0) // false (out of range)

8. Network Validation

IP / IPv4 / IPv6

func IP(str string) bool
func IPv4(str string) bool
func IPv6(str string) bool

Examples:

// IPv4
is.IPv4("192.168.1.1") // true
is.IPv4("8.8.8.8") // true
is.IPv4("127.0.0.1") // true
is.IPv4("2001:db8::1") // false (IPv6 format)

// IPv6
is.IPv6("2001:db8::1") // true
is.IPv6("::1") // true (localhost)
is.IPv6("fe80::1") // true (link-local)
is.IPv6("192.168.1.1") // false (IPv4 format)

// IP (any version)
is.IP("192.168.1.1") // true
is.IP("2001:db8::1") // true

MAC - MAC Address

func MAC(str string) bool

Examples:

is.MAC("00:00:5e:00:53:01")   // true (colon-separated)
is.MAC("00-00-5e-00-53-01") // true (hyphen-separated)
is.MAC("aa:bb:cc:dd:ee:ff") // true
is.MAC("00:00:5e:00:53") // false (insufficient bytes)

E164 - International Phone Number

func E164(str string) bool

Description: E.164 is the international phone number format, format: +[country code][number].

Examples:

is.E164("+14155552671")       // true (USA)
is.E164("+8613800138000") // true (China)
is.E164("14155552671") // false (missing +)
is.E164("+123") // false (too short)

9. Data Format Validation

JSON - JSON Validation

func JSON[T any](t T) bool

Examples:

is.JSON(`{"name": "John", "age": 30}`)  // true
is.JSON([]byte(`[1, 2, 3]`)) // true
is.JSON("invalid json") // false
is.JSON(123) // false

HTML - HTML Tag Detection

func HTML(str string) bool

Examples:

is.HTML("<div>content</div>")           // true
is.HTML("<p>Hello World</p>") // true
is.HTML("Hello World") // false

Semver - Semantic Versioning

func Semver(s string) bool

Description: Validates compliance with Semantic Versioning 2.0.0 specification, format: MAJOR.MINOR.PATCH[-PRERELEASE][+BUILD].

Examples:

is.Semver("1.0.0")                      // true
is.Semver("2.1.3-beta.2+exp.sha.5114f85") // true
is.Semver("1.0") // false (missing PATCH)
is.Semver("v1.0.0") // false (doesn't support v prefix)

Label - Label/Variable Name Validation

func Label(s string) bool

Description: Validates compliance with variable naming conventions. Must start with a letter (A-F), followed by letters, digits, or underscores.

Examples:

is.Label("API_HOST")         // true
is.Label("config_debug") // true
is.Label("1INVALID") // false (starts with digit)
is.Label("api-host") // false (contains hyphen)

Datetime - Date/Time Validation

func Datetime(str, layout string) bool

Description: Validates whether a string matches the specified time format.

Examples:

is.Datetime("2023-12-25", "2006-01-02")         // true
is.Datetime("10:30:45", "15:04:05") // true
is.Datetime("2023-12-25 10:30:45", time.RFC3339) // true
is.Datetime("invalid", "2006-01-02") // false

Timezone - Timezone Validation

func Timezone(str string) bool

Description: Validates whether it's a valid IANA timezone identifier.

Examples:

is.Timezone("America/New_York")  // true
is.Timezone("UTC") // true
is.Timezone("Asia/Shanghai") // true
is.Timezone("Invalid/Zone") // false

10. File System Validation

File / Dir

func File(val any) bool
func Dir(val any) bool

Examples:

// File check
is.File("/etc/hosts") // true (if file exists)
is.File("./config.json") // true (if file exists)
is.File("/tmp") // false (is a directory)

// Directory check
is.Dir("/tmp") // true (if directory exists)
is.Dir("./") // true (current directory)
is.Dir("/etc/hosts") // false (is a file)

11. General Validation

Empty / NotEmpty

func Empty[T any](t T) bool
func NotEmpty[T any](t T) bool

Description: Checks whether a value is empty. Definition of empty value:

  • String, array, slice, map: length 0
  • Integer, float: value 0
  • Boolean: false
  • Pointer, interface, channel, function: nil
  • time.Time: zero value

Examples:

is.Empty("")                  // true
is.Empty(0) // true
is.Empty(false) // true
is.Empty([]string{}) // true
is.Empty(nil) // true
is.Empty(time.Time{}) // true

is.NotEmpty("hello") // true
is.NotEmpty(42) // true
is.NotEmpty([]int{1, 2, 3}) // true

HasValue / Default

func HasValue(val any) bool
func Default(val any) bool // Reverse of HasValue

Description: Checks whether a value is not the default static value.

Examples:

is.HasValue("hello")      // true
is.HasValue(42) // true
is.HasValue(nil) // false
is.HasValue(0) // false

is.Default(0) // true
is.Default("") // true
is.Default(nil) // true

Boolean - Boolean Value Check

func Boolean[T any](t T) bool

Description: Checks whether a value can be safely converted to a boolean.

Supported values:

  • Strings: "1", "yes", "YES", "on", "ON", "true", "TRUE", "0", "no", "NO", "off", "OFF", "false", "FALSE"
  • Integers: 0 or 1
  • Boolean: true or false

Examples:

is.Boolean("true")        // true
is.Boolean("yes") // true
is.Boolean(1) // true
is.Boolean(0) // true
is.Boolean(true) // true
is.Boolean("maybe") // false
is.Boolean(2) // false

OneOf - Candidate Value Check

func OneOf(val any, vals []any) bool

Description: Checks whether a value is in the allowed candidate list.

Examples:

is.OneOf("apple", []any{"apple", "banana", "orange"})  // true
is.OneOf(5, []any{1, 2, 3, 4, 5}) // true
is.OneOf("red", []any{"green", "blue"}) // false
is.OneOf("test", []any{}) // false

12. Comparison Validation

Compare - General Comparison

func Compare(srcVal, dstVal any, op string) bool

Supported operators:

  • "=": Equal
  • "!=": Not equal
  • "<": Less than
  • "<=": Less than or equal
  • ">": Greater than
  • ">=": Greater than or equal

Examples:

is.Compare(2, 3, ">")         // false
is.Compare(2, 1.3, ">") // true
is.Compare("apple", "banana", "<") // true (lexicographic order)
is.Compare(true, false, ">") // true
is.Compare(time.Now(), time.Now().Add(-time.Hour), ">") // true

Convenience Comparison Functions

func Equal(a, b any) bool
func NotEqual(a, b any) bool
func GreaterThan(a, b any) bool
func GreaterEqualThan(a, b any) bool
func LessThan(a, b any) bool
func LessEqualThan(a, b any) bool

Examples:

is.Equal(10, 10)              // true
is.NotEqual(10, 5) // true
is.GreaterThan(10, 5) // true
is.GreaterEqualThan(10, 10) // true
is.LessThan(5, 10) // true
is.LessEqualThan(10, 10) // true

Between / NotBetween - Range Check

func Between(val, min, max any) bool
func NotBetween(val, min, max any) bool

Description: Checks whether a value is (or is not) within the specified closed interval. Requires min < max, otherwise will panic.

Examples:

is.Between(5, 1, 10)          // true
is.Between(10, 1, 10) // true (boundary value)
is.Between(0, 1, 10) // false
is.Between("m", "a", "z") // true (lexicographic order)

is.NotBetween(0, 1, 10) // true
is.NotBetween(11, 1, 10) // true
is.NotBetween(5, 1, 10) // false

13. Length Validation

Length - Length Comparison

func Length(val any, length int, op string) bool

Description: Validates whether the length of a value meets the specified condition. Supports strings, arrays, slices, maps, channels.

Examples:

is.Length("hello", 5, "=")         // true
is.Length([]int{1, 2, 3}, 3, "=") // true
is.Length("world", 5, ">=") // true
is.Length("test", 5, "<") // true
is.Length(123, 3, "=") // false (doesn't support numbers)

LengthBetween - Length Range

func LengthBetween(val any, min, max int) bool

Description: Checks whether the length of a value is within the specified range (closed interval).

Examples:

is.LengthBetween("hello", 3, 8)        // true (length 5)
is.LengthBetween([]int{1, 2, 3}, 2, 5) // true (length 3)
is.LengthBetween("world", 1, 4) // false (length 5 exceeds)
is.LengthBetween("test", 6, 10) // false (length 4 insufficient)

Use Cases

1. Form Validation

type UserForm struct {
Email string
Phone string
Age int
Website string
}

func ValidateUserForm(form *UserForm) map[string]string {
errors := make(map[string]string)

// Email validation
if !is.Email(form.Email) {
errors["email"] = "Invalid email address"
}

// Phone number validation
if !is.PhoneNumber(form.Phone) {
errors["phone"] = "Invalid phone number"
}

// Age range validation
if !is.Between(form.Age, 18, 120) {
errors["age"] = "Age must be between 18-120"
}

// Website validation (optional)
if form.Website != "" && !is.URL(form.Website) {
errors["website"] = "Invalid website URL"
}

return errors
}

2. API Input Validation

type CreateProductRequest struct {
Name string
SKU string
Price float64
Stock int
Color string
Description string
}

func ValidateProduct(req *CreateProductRequest) error {
// Name cannot be empty
if is.Empty(req.Name) {
return fmt.Errorf("Product name cannot be empty")
}

// Name length limit
if !is.LengthBetween(req.Name, 3, 100) {
return fmt.Errorf("Product name length must be between 3-100 characters")
}

// SKU format validation (alphanumeric)
if !is.Alphanumeric(req.SKU) {
return fmt.Errorf("SKU can only contain letters and numbers")
}

// Price range
if !is.GreaterThan(req.Price, 0.0) {
return fmt.Errorf("Price must be greater than 0")
}

// Stock range
if !is.Between(req.Stock, 0, 999999) {
return fmt.Errorf("Stock must be between 0-999999")
}

// Color validation (optional)
if req.Color != "" && !is.Color(req.Color) {
return fmt.Errorf("Invalid color value")
}

// Description length limit
if !is.Empty(req.Description) && !is.Length(req.Description, 1000, "<=") {
return fmt.Errorf("Description cannot exceed 1000 characters")
}

return nil
}

3. Configuration Validation

type ServerConfig struct {
Host string
Port int
SSL bool
CertFile string
KeyFile string
}

func ValidateServerConfig(cfg *ServerConfig) error {
// Host validation (IP or domain)
if !is.IP(cfg.Host) && !is.Alpha(cfg.Host) {
return fmt.Errorf("Invalid host address: %s", cfg.Host)
}

// Port range
if !is.Between(cfg.Port, 1, 65535) {
return fmt.Errorf("Port must be between 1-65535")
}

// SSL configuration validation
if cfg.SSL {
if is.Empty(cfg.CertFile) {
return fmt.Errorf("Certificate file must be provided when SSL is enabled")
}
if is.Empty(cfg.KeyFile) {
return fmt.Errorf("Key file must be provided when SSL is enabled")
}

// Check if files exist
if !is.File(cfg.CertFile) {
return fmt.Errorf("Certificate file does not exist: %s", cfg.CertFile)
}
if !is.File(cfg.KeyFile) {
return fmt.Errorf("Key file does not exist: %s", cfg.KeyFile)
}
}

return nil
}

4. Data Filtering and Cleaning

type DataFilter struct {
AllowedIPs []string
AllowedEmails []string
BlockedWords []string
}

func FilterUserInput(input map[string]any, filter *DataFilter) (map[string]any, error) {
cleaned := make(map[string]any)

for key, value := range input {
// Handle string values
if strVal, ok := value.(string); ok {
// HTML injection check
if is.HTML(strVal) {
return nil, fmt.Errorf("HTML tags detected: %s", key)
}

// Remove URL-encoded content
if is.URLEncoded(strVal) {
// Decode processing...
}

cleaned[key] = strVal
}

// Handle IP address
if key == "ip" {
if ipStr, ok := value.(string); ok {
if !is.IP(ipStr) {
return nil, fmt.Errorf("Invalid IP address: %s", ipStr)
}
// Check if in allowed list
if !is.OneOf(ipStr, toAnySlice(filter.AllowedIPs)) {
return nil, fmt.Errorf("IP address not in allowed list: %s", ipStr)
}
cleaned[key] = ipStr
}
}

// Handle email
if key == "email" {
if emailStr, ok := value.(string); ok {
if !is.Email(emailStr) {
return nil, fmt.Errorf("Invalid email address: %s", emailStr)
}
cleaned[key] = strings.ToLower(emailStr)
}
}
}

return cleaned, nil
}

5. Database Model Validation

type User struct {
ID string
Username string
Email string
Phone string
Avatar string
Bio string
Website string
Location struct {
Lat float64
Lng float64
}
}

func (u *User) Validate() error {
// ID must be UUID
if !is.UUID(u.ID) {
return fmt.Errorf("Invalid user ID")
}

// Username: alphanumeric, 3-20 characters
if !is.Alphanumeric(u.Username) {
return fmt.Errorf("Username can only contain letters and numbers")
}
if !is.LengthBetween(u.Username, 3, 20) {
return fmt.Errorf("Username length must be between 3-20 characters")
}

// Email validation
if !is.Email(u.Email) {
return fmt.Errorf("Invalid email address")
}

// Phone number validation (optional)
if u.Phone != "" && !is.PhoneNumber(u.Phone) {
return fmt.Errorf("Invalid phone number")
}

// Avatar URL validation (optional)
if u.Avatar != "" && !is.URL(u.Avatar) {
return fmt.Errorf("Invalid avatar URL")
}

// Bio length limit
if !is.Empty(u.Bio) && !is.Length(u.Bio, 500, "<=") {
return fmt.Errorf("Bio cannot exceed 500 characters")
}

// Website URL validation (optional)
if u.Website != "" && !is.URL(u.Website) {
return fmt.Errorf("Invalid website URL")
}

// Geographic coordinate validation
if !is.Latitude(u.Location.Lat) {
return fmt.Errorf("Invalid latitude value")
}
if !is.Longitude(u.Location.Lng) {
return fmt.Errorf("Invalid longitude value")
}

return nil
}

6. Middleware Validation

func ValidateRequestMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
// Validate Content-Type
contentType := c.GetHeader("Content-Type")
if is.Empty(contentType) {
c.AbortWithStatusJSON(400, gin.H{"error": "Content-Type is required"})
return
}

// Validate client IP
clientIP := c.ClientIP()
if !is.IP(clientIP) {
c.AbortWithStatusJSON(400, gin.H{"error": "Invalid client IP"})
return
}

// Validate Authorization token (JWT)
if token := c.GetHeader("Authorization"); token != "" {
// Remove "Bearer " prefix
token = strings.TrimPrefix(token, "Bearer ")
if !is.JWT(token) {
c.AbortWithStatusJSON(401, gin.H{"error": "Invalid JWT token"})
return
}
}

// Validate API Key (if exists)
if apiKey := c.GetHeader("X-API-Key"); apiKey != "" {
if !is.UUID(apiKey) {
c.AbortWithStatusJSON(401, gin.H{"error": "Invalid API key"})
return
}
}

c.Next()
}
}

API Reference

String Format

FunctionDescription
Email(str string) boolEmail address
PhoneNumber(s string) boolChinese phone number
Idcard(s string) boolChinese ID card number
URL(s string) boolURL
E164(str string) boolE.164 international phone

Unique Identifiers

FunctionDescription
UUID(str string) boolUUID (any version)
UUID3/4/5(str string) boolSpecific version UUID
ULID(str string) boolULID

Hash Values

FunctionDescription
MD4/MD5(str string) boolMD4/MD5 hash
SHA256/384/512(str string) boolSHA series hash

Encoding

FunctionDescription
Base64(s string) boolBase64 encoding
Base64URL(str string) boolURL-safe Base64
JWT(str string) boolJSON Web Token
URLEncoded(str string) boolURL encoding
HTMLEncoded(str string) boolHTML entity encode

Character Types

FunctionDescription
ASCII(str string) boolASCII characters
Alpha(str string) boolLetters only
Alphanumeric(str string) boolLetters + digits
AlphaUnicode(str string) boolUnicode letters
AlphanumericUnicode(str string) boolUnicode letters+digits
Numeric[T](t T) boolNumeric type
Number[T](t T) boolPure number
Hexadecimal(str string) boolHexadecimal
Lowercase(str string) boolLowercase letters
Uppercase(str string) boolUppercase letters

Colors

FunctionDescription
HEXColor(str string) boolHEX color
RGB/RGBA(str string) boolRGB/RGBA color
HSL/HSLA(str string) boolHSL/HSLA color
Color(str string) boolAny color format

Geography and Network

FunctionDescription
Latitude[T](t T) boolLatitude
Longitude[T](t T) boolLongitude
IP(str string) boolIP address
IPv4/IPv6(str string) boolIPv4/IPv6
MAC(str string) boolMAC address

Data Formats

FunctionDescription
JSON[T](t T) boolJSON data
HTML(str string) boolHTML tag
Semver(s string) boolSemantic version
Label(s string) boolLabel/variable name
Datetime(str, layout string) boolDate/time
Timezone(str string) boolTimezone

File System

FunctionDescription
File(val any) boolFile exists
Dir(val any) boolDirectory exists

General Validation

FunctionDescription
Empty[T](t T) boolIs empty
NotEmpty[T](t T) boolIs not empty
HasValue(val any) boolHas value
Default(val any) boolIs default value
Boolean[T](t T) boolBoolean check
OneOf(val any, vals []any) boolCandidate check

Comparison

FunctionDescription
Compare(src, dst any, op string) boolGeneral comparison
Equal/NotEqual(a, b any) boolEqual/Not equal
GreaterThan/LessThan(a, b any) boolGreater/Less than
GreaterEqualThan/LessEqualThan(a, b any) boolGreater/Less or equal
Between(val, min, max any) boolWithin range
NotBetween(val, min, max any) boolOutside range

Length

FunctionDescription
Length(val any, length int, op string) boolLength comparison
LengthBetween(val any, min, max int) boolLength range

Notes

1. Generic Functions

Some functions use generics to support multiple types:

// Supports multiple types
is.Numeric(123) // int
is.Numeric(45.67) // float64
is.Numeric("123") // string

// Type-safe validation
is.Empty([]int{}) // Empty slice
is.Empty("") // Empty string
is.Empty(0) // Zero value

2. Regular Expression Performance

Most validation functions use precompiled regular expressions, optimized for performance. Frequent calls won't have performance issues.

3. China-Specific Functions

The library includes validation functions specifically designed for China:

// Phone number validation (China mainland format only)
is.PhoneNumber("13800138000")

// ID card number validation (Chinese format)
is.Idcard("11010519491231002X")

4. File System Validation

File and directory validation actually checks the file system:

// Actually checks if file exists
is.File("/path/to/file") // Accesses file system

// Ensure path is valid before use
if is.File(path) {
// File exists, can read
}

5. Empty Value Handling

Understand the difference between Empty vs HasValue vs Default:

is.Empty("")          // true  (length 0)
is.Empty(0) // true (zero value)
is.Empty(nil) // true (nil)

is.HasValue("") // false (default value)
is.HasValue(0) // false (default value)
is.HasValue(42) // true (non-default value)

is.Default("") // true (equivalent to !HasValue)
is.Default(42) // false

6. Compare Operation Type Support

Types supported by the Compare function:

  • Numeric types (int, float, uint series)
  • Strings (lexicographic order comparison)
  • Boolean (true > false)
  • time.Time (chronological order)

Unsupported types fall back to == and != operations.

7. Range Validation Boundaries

Both Between and LengthBetween use closed intervals (include boundaries):

is.Between(1, 1, 10)   // true (1 >= 1 and 1 <= 10)
is.Between(10, 1, 10) // true (10 >= 1 and 10 <= 10)
is.Between(0, 1, 10) // false (0 < 1)

8. Error Handling

Some functions may panic:

// Between requires min < max, otherwise panics
is.Between(5, 10, 1) // panic: ErrBadRange

Ensure parameters are valid before use.


Best Practices

1. Combined Validation

func ValidateUsername(username string) error {
if is.Empty(username) {
return errors.New("Username cannot be empty")
}

if !is.Alphanumeric(username) {
return errors.New("Username can only contain letters and numbers")
}

if !is.LengthBetween(username, 3, 20) {
return errors.New("Username length must be between 3-20 characters")
}

return nil
}

2. Custom Validators

type Validator func(any) error

func ChainValidators(validators ...Validator) Validator {
return func(val any) error {
for _, v := range validators {
if err := v(val); err != nil {
return err
}
}
return nil
}
}

// Usage
emailValidator := func(val any) error {
if str, ok := val.(string); !ok || !is.Email(str) {
return errors.New("Invalid email")
}
return nil
}

lengthValidator := func(val any) error {
if str, ok := val.(string); !ok || !is.LengthBetween(str, 5, 100) {
return errors.New("Length must be between 5-100")
}
return nil
}

validate := ChainValidators(emailValidator, lengthValidator)

3. Struct Validation

type ValidatableStruct interface {
Validate() error
}

func ValidateStruct(v ValidatableStruct) error {
return v.Validate()
}

// Usage
type User struct {
Email string
Age int
}

func (u *User) Validate() error {
if !is.Email(u.Email) {
return errors.New("invalid email")
}
if !is.Between(u.Age, 0, 150) {
return errors.New("invalid age")
}
return nil
}

4. Error Message Internationalization

var validationMessages = map[string]string{
"email_invalid": "Invalid email address",
"phone_invalid": "Invalid phone number",
// ...
}

func ValidateWithMessage(value any, validator func(any) bool, msgKey string) error {
if !validator(value) {
if msg, ok := validationMessages[msgKey]; ok {
return errors.New(msg)
}
return errors.New("Validation failed")
}
return nil
}