Slim

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 mainimport (    "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")      // trueis.Email("user+tag@domain.org")   // trueis.Email("用户@example.cn")        // true (supports internationalization)is.Email("invalid-email")         // falseis.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")      // trueis.PhoneNumber("+8613800138000")   // trueis.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")        // trueis.URL("ftp://user:pass@host/path")  // trueis.URL("http://localhost:8080")      // trueis.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 versionfunc 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")  // trueis.UUID4("6ba7b810-9dad-11d1-80b4-00c04fd430c8")  // false (v3)// UUID v3is.UUID3("6ba7b810-9dad-11d1-80b4-00c04fd430c8")  // true// UUID v5is.UUID5("6ba7b810-9dad-11d1-80b4-00c04fd430c8")  // true// Any versionis.UUID("550e8400-e29b-41d4-a716-446655440000")   // trueis.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")  // trueis.ULID("01BX5ZZKBKACTAV9WEVGEMMVR0")  // trueis.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:

// MD5is.MD5("5d41402abc4b2a76b9719d911017c592")  // true ("hello")is.MD5("invalid-hash")                      // false// SHA-256is.SHA256("2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824")  // true ("hello")// SHA-512is.SHA512("9b71d224bd62f3785d96d46ad3ea3d73319bfbc2890caadae2dff72519673ca72323c3d99ba5c11d7c7acc6e14b8c5da0c4663475c2e5c3adef46f73bcdec043")  // true ("hello")

4. Encoding Validation

Base64 - Base64 Encoding

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

Examples:

// Standard Base64is.Base64("SGVsbG8gV29ybGQ=")     // true ("Hello World")is.Base64("Hello World")          // false (not encoded)// URL-safe Base64is.Base64URL("SGVsbG8gV29ybGQ")   // trueis.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")  // trueis.JWT("invalid.jwt")  // false

URLEncoded / HTMLEncoded

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

Examples:

// URL encodingis.URLEncoded("Hello%20World")      // trueis.URLEncoded("name%3Dvalue")       // trueis.URLEncoded("Hello World")        // false// HTML entity encodingis.HTMLEncoded("Hello&World")   // trueis.HTMLEncoded("<div>")       // trueis.HTMLEncoded("Hello & World")     // false

5. Character Type Validation

ASCII / Alpha / Alphanumeric

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

Examples:

// ASCII charactersis.ASCII("Hello World")    // trueis.ASCII("Héllo")          // false (contains non-ASCII character)// Letters onlyis.Alpha("Hello")          // trueis.Alpha("Hello123")       // false (contains digits)// Letters + digitsis.Alphanumeric("Hello123")   // trueis.Alphanumeric("Hello-123")  // false (contains hyphen)// Unicode lettersis.AlphaUnicode("Héllo")      // trueis.AlphaUnicode("你好")        // trueis.AlphaUnicode("Привет")     // true (Russian)// Unicode letters + digitsis.AlphanumericUnicode("Café123")  // trueis.AlphanumericUnicode("你好123")   // true

Numeric / Number / Hexadecimal

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

Examples:

// Numeric type (including negative, decimal)is.Numeric(123)        // trueis.Numeric(-45.67)     // trueis.Numeric("123")      // trueis.Numeric("abc")      // false// Pure number (integer)is.Number(123)         // trueis.Number("123")       // trueis.Number(-45)         // false (negative)is.Number("12.34")     // false (decimal)// Hexadecimalis.Hexadecimal("FF00AA")   // trueis.Hexadecimal("123abc")   // trueis.Hexadecimal("FFGG")     // false (G is not hexadecimal)

Lowercase / Uppercase

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

Examples:

// Lowercaseis.Lowercase("hello world")   // trueis.Lowercase("Hello World")   // false// Uppercaseis.Uppercase("HELLO WORLD")   // trueis.Uppercase("Hello World")   // false

6. Color Validation

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

Examples:

// HEX coloris.HEXColor("#FF0000")          // true (red)is.HEXColor("#F00")             // true (short format)is.HEXColor("#FF000080")        // true (with transparency)// RGBis.RGB("rgb(255, 0, 0)")        // true (red)is.RGB("rgb(255,255,255)")      // true (white)// RGBAis.RGBA("rgba(255, 0, 0, 0.5)")  // true (semi-transparent red)// HSLis.HSL("hsl(0, 100%, 50%)")      // true (red)// HSLAis.HSLA("hsla(0, 100%, 50%, 0.5)")  // true (semi-transparent red)// Universal color validationis.Color("#FF0000")                  // trueis.Color("rgb(255, 0, 0)")           // trueis.Color("hsl(0, 100%, 50%)")        // true

7. Geographic Coordinate Validation

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

Description:

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

Examples:

// Latitudeis.Latitude(45.0)        // trueis.Latitude(-90.0)       // true (South Pole)is.Latitude("90.0")      // true (North Pole)is.Latitude(91.0)        // false (out of range)// Longitudeis.Longitude(120.0)      // trueis.Longitude(-180.0)     // trueis.Longitude("180.0")    // trueis.Longitude(181.0)      // false (out of range)

8. Network Validation

IP / IPv4 / IPv6

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

Examples:

// IPv4is.IPv4("192.168.1.1")        // trueis.IPv4("8.8.8.8")            // trueis.IPv4("127.0.0.1")          // trueis.IPv4("2001:db8::1")        // false (IPv6 format)// IPv6is.IPv6("2001:db8::1")        // trueis.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")          // trueis.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")   // trueis.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}`)  // trueis.JSON([]byte(`[1, 2, 3]`))            // trueis.JSON("invalid json")                  // falseis.JSON(123)                             // false

HTML - HTML Tag Detection

func HTML(str string) bool

Examples:

is.HTML("<div>content</div>")           // trueis.HTML("<p>Hello World</p>")           // trueis.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")                      // trueis.Semver("2.1.3-beta.2+exp.sha.5114f85")  // trueis.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")         // trueis.Label("config_debug")     // trueis.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")         // trueis.Datetime("10:30:45", "15:04:05")             // trueis.Datetime("2023-12-25 10:30:45", time.RFC3339)  // trueis.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")  // trueis.Timezone("UTC")               // trueis.Timezone("Asia/Shanghai")     // trueis.Timezone("Invalid/Zone")      // false

10. File System Validation

File / Dir

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

Examples:

// File checkis.File("/etc/hosts")            // true (if file exists)is.File("./config.json")         // true (if file exists)is.File("/tmp")                  // false (is a directory)// Directory checkis.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) boolfunc 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("")                  // trueis.Empty(0)                   // trueis.Empty(false)               // trueis.Empty([]string{})          // trueis.Empty(nil)                 // trueis.Empty(time.Time{})         // trueis.NotEmpty("hello")          // trueis.NotEmpty(42)               // trueis.NotEmpty([]int{1, 2, 3})   // true

HasValue / Default

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

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

Examples:

is.HasValue("hello")      // trueis.HasValue(42)           // trueis.HasValue(nil)          // falseis.HasValue(0)            // falseis.Default(0)             // trueis.Default("")            // trueis.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")        // trueis.Boolean("yes")         // trueis.Boolean(1)             // trueis.Boolean(0)             // trueis.Boolean(true)          // trueis.Boolean("maybe")       // falseis.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"})  // trueis.OneOf(5, []any{1, 2, 3, 4, 5})                     // trueis.OneOf("red", []any{"green", "blue"})               // falseis.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, ">")         // falseis.Compare(2, 1.3, ">")       // trueis.Compare("apple", "banana", "<")  // true (lexicographic order)is.Compare(true, false, ">")  // trueis.Compare(time.Now(), time.Now().Add(-time.Hour), ">")  // true

Convenience Comparison Functions

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

Examples:

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

Between / NotBetween - Range Check

func Between(val, min, max any) boolfunc 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)          // trueis.Between(10, 1, 10)         // true (boundary value)is.Between(0, 1, 10)          // falseis.Between("m", "a", "z")     // true (lexicographic order)is.NotBetween(0, 1, 10)       // trueis.NotBetween(11, 1, 10)      // trueis.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, "=")         // trueis.Length([]int{1, 2, 3}, 3, "=")  // trueis.Length("world", 5, ">=")        // trueis.Length("test", 5, "<")          // trueis.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 typesis.Numeric(123)        // intis.Numeric(45.67)      // float64is.Numeric("123")      // string// Type-safe validationis.Empty([]int{})      // Empty sliceis.Empty("")           // Empty stringis.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 existsis.File("/path/to/file")  // Accesses file system// Ensure path is valid before useif 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 panicsis.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) errorfunc ChainValidators(validators ...Validator) Validator {    return func(val any) error {        for _, v := range validators {            if err := v(val); err != nil {                return err            }        }        return nil    }}// UsageemailValidator := 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()}// Usagetype 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}

Navigate Select esc Close search