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/isQuick 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) boolDescription: 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) boolDescription: 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) boolDescription: 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) boolDescription: 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") // falseULID - Sortable Unique Identifier
func ULID(str string) boolDescription: 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") // false3. 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 Base64Examples:
// 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) boolDescription: 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") // falseURLEncoded / HTMLEncoded
func URLEncoded(str string) boolfunc HTMLEncoded(str string) boolExamples:
// 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") // false5. 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) boolExamples:
// 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") // trueNumeric / Number / Hexadecimal
func Numeric[T any](t T) boolfunc Number[T any](t T) boolfunc Hexadecimal(str string) boolExamples:
// 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) boolExamples:
// Lowercaseis.Lowercase("hello world") // trueis.Lowercase("Hello World") // false// Uppercaseis.Uppercase("HELLO WORLD") // trueis.Uppercase("Hello World") // false6. 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 formatsExamples:
// 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%)") // true7. Geographic Coordinate Validation
func Latitude[T any](t T) boolfunc Longitude[T any](t T) boolDescription:
- 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) boolExamples:
// 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") // trueMAC - MAC Address
func MAC(str string) boolExamples:
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) boolDescription: 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) boolExamples:
is.JSON(`{"name": "John", "age": 30}`) // trueis.JSON([]byte(`[1, 2, 3]`)) // trueis.JSON("invalid json") // falseis.JSON(123) // falseHTML - HTML Tag Detection
func HTML(str string) boolExamples:
is.HTML("<div>content</div>") // trueis.HTML("<p>Hello World</p>") // trueis.HTML("Hello World") // falseSemver - Semantic Versioning
func Semver(s string) boolDescription: 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) boolDescription: 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) boolDescription: 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") // falseTimezone - Timezone Validation
func Timezone(str string) boolDescription: 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") // false10. File System Validation
File / Dir
func File(val any) boolfunc Dir(val any) boolExamples:
// 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) boolDescription: 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}) // trueHasValue / Default
func HasValue(val any) boolfunc Default(val any) bool // Reverse of HasValueDescription: 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) // trueBoolean - Boolean Value Check
func Boolean[T any](t T) boolDescription: 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) // falseOneOf - Candidate Value Check
func OneOf(val any, vals []any) boolDescription: 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{}) // false12. Comparison Validation
Compare - General Comparison
func Compare(srcVal, dstVal any, op string) boolSupported 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), ">") // trueConvenience 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) boolExamples:
is.Equal(10, 10) // trueis.NotEqual(10, 5) // trueis.GreaterThan(10, 5) // trueis.GreaterEqualThan(10, 10) // trueis.LessThan(5, 10) // trueis.LessEqualThan(10, 10) // trueBetween / NotBetween - Range Check
func Between(val, min, max any) boolfunc NotBetween(val, min, max any) boolDescription: 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) // false13. Length Validation
Length - Length Comparison
func Length(val any, length int, op string) boolDescription: 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) boolDescription: 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
| Function | Description |
|---|---|
Email(str string) bool | Email address |
PhoneNumber(s string) bool | Chinese phone number |
Idcard(s string) bool | Chinese ID card number |
URL(s string) bool | URL |
E164(str string) bool | E.164 international phone |
Unique Identifiers
| Function | Description |
|---|---|
UUID(str string) bool | UUID (any version) |
UUID3/4/5(str string) bool | Specific version UUID |
ULID(str string) bool | ULID |
Hash Values
| Function | Description |
|---|---|
MD4/MD5(str string) bool | MD4/MD5 hash |
SHA256/384/512(str string) bool | SHA series hash |
Encoding
| Function | Description |
|---|---|
Base64(s string) bool | Base64 encoding |
Base64URL(str string) bool | URL-safe Base64 |
JWT(str string) bool | JSON Web Token |
URLEncoded(str string) bool | URL encoding |
HTMLEncoded(str string) bool | HTML entity encode |
Character Types
| Function | Description |
|---|---|
ASCII(str string) bool | ASCII characters |
Alpha(str string) bool | Letters only |
Alphanumeric(str string) bool | Letters + digits |
AlphaUnicode(str string) bool | Unicode letters |
AlphanumericUnicode(str string) bool | Unicode letters+digits |
Numeric[T](t T) bool | Numeric type |
Number[T](t T) bool | Pure number |
Hexadecimal(str string) bool | Hexadecimal |
Lowercase(str string) bool | Lowercase letters |
Uppercase(str string) bool | Uppercase letters |
Colors
| Function | Description |
|---|---|
HEXColor(str string) bool | HEX color |
RGB/RGBA(str string) bool | RGB/RGBA color |
HSL/HSLA(str string) bool | HSL/HSLA color |
Color(str string) bool | Any color format |
Geography and Network
| Function | Description |
|---|---|
Latitude[T](t T) bool | Latitude |
Longitude[T](t T) bool | Longitude |
IP(str string) bool | IP address |
IPv4/IPv6(str string) bool | IPv4/IPv6 |
MAC(str string) bool | MAC address |
Data Formats
| Function | Description |
|---|---|
JSON[T](t T) bool | JSON data |
HTML(str string) bool | HTML tag |
Semver(s string) bool | Semantic version |
Label(s string) bool | Label/variable name |
Datetime(str, layout string) bool | Date/time |
Timezone(str string) bool | Timezone |
File System
| Function | Description |
|---|---|
File(val any) bool | File exists |
Dir(val any) bool | Directory exists |
General Validation
| Function | Description |
|---|---|
Empty[T](t T) bool | Is empty |
NotEmpty[T](t T) bool | Is not empty |
HasValue(val any) bool | Has value |
Default(val any) bool | Is default value |
Boolean[T](t T) bool | Boolean check |
OneOf(val any, vals []any) bool | Candidate check |
Comparison
| Function | Description |
|---|---|
Compare(src, dst any, op string) bool | General comparison |
Equal/NotEqual(a, b any) bool | Equal/Not equal |
GreaterThan/LessThan(a, b any) bool | Greater/Less than |
GreaterEqualThan/LessEqualThan(a, b any) bool | Greater/Less or equal |
Between(val, min, max any) bool | Within range |
NotBetween(val, min, max any) bool | Outside range |
Length
| Function | Description |
|---|---|
Length(val any, length int, op string) bool | Length comparison |
LengthBetween(val any, min, max int) bool | Length 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 value2. 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) // false6. 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: ErrBadRangeEnsure 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}