validate

package
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: Aug 11, 2025 License: MIT Imports: 12 Imported by: 0

README

Validate

Tiny, type-safe helpers for runtime validation of numbers, strings, collections, and formats.

Usage Example

package main

import (
    "fmt"
    "regexp"
    "github.com/kaptinlin/gozod/pkg/validate"
)

type User struct {
    Email string
    Age   int
    Tags  []string
}

func main() {
    // Struct field validation
    u := User{Email: "alice@example.com", Age: 27, Tags: []string{"go", "dev"}}
    profileOK := validate.Email(u.Email) &&
        validate.Positive(u.Age) &&
        validate.MinSize(u.Tags, 1) &&
        validate.MaxSize(u.Tags, 5)
    fmt.Println("profile valid:", profileOK) // true

    // Map property validation (e.g. HTTP headers)
    headers := map[string]any{
        "X-Auth":  "aabbccddeeff00112233445566778899",
        "Version": "v1.2.3",
    }
    hex32 := regexp.MustCompile(`^[0-9a-f]{32}$`)
    if validate.Property(headers, "X-Auth", func(v any) bool {
        return validate.Regex(v, hex32)
    }) {
        fmt.Println("header OK")
    }

    // Numeric rules
    score := 80
    if validate.MultipleOf(score, 10) && validate.Lte(score, 100) {
        fmt.Println("score looks good")
    }
}

Quick Reference

import "github.com/kaptinlin/gozod/pkg/validate"

// Numeric comparisons
validate.Lt(3, 5)            // true
validate.Lte(10, 10)         // true
validate.Gt(a, b)            // a > b
validate.Gte(a, b)           // a >= b
validate.Positive(-1)        // false
validate.Negative(n)         // n < 0
validate.NonPositive(n)      // n <= 0
validate.NonNegative(n)      // n >= 0
validate.MultipleOf(10, 2)   // true

// Length & size
validate.MaxLength("hello", 10)         // true
validate.MinLength("go", 3)             // false
validate.Length("abc", 3)               // true
validate.Size([]int{1, 2, 3}, 3)        // true
validate.MinSize(map[string]int{"a":1}, 1) // true
validate.MaxSize([]string{"a", "b"}, 2)   // true

// String & regex
validate.Lowercase("abc")               // true
validate.Uppercase("ABC")               // true
validate.Includes("gopher", "go")        // true
validate.StartsWith("prefix", "pre")      // true
validate.EndsWith("suffix", "fix")        // true
validate.Regex("alice@example.com", regexes.Email) // true

// Formats & network
validate.Email("bob@example.com")        // true
validate.URL("https://example.com")      // true
validate.UUID("uuid-string")             // true/false
validate.IPv4("192.168.0.1")             // true
validate.CIDRv4("10.0.0.0/24")           // true
validate.ISODateTime("2024-06-12T08:04:00Z") // true
validate.ISODate("2024-06-12")           // true
validate.ISOTime("08:04:00Z")            // true
validate.ISODuration("P1DT2H")           // true

// Encoding & tokens
validate.Base64("aGVsbG8=")              // true
validate.Base64URL("aGVsbG8t")           // true
validate.JWT("eyJhbGciOiJI...")           // true/false

// Object property
headers := map[string]any{"X-Auth": "aabbccddeeff00112233445566778899"}
hex32 := regexp.MustCompile(`^[0-9a-f]{32}$`)
validate.Property(headers, "X-Auth", func(v any) bool {
    return validate.Regex(v, hex32)
}) // true

// MIME
validate.Mime("image/png", []string{"image/png", "image/jpeg"}) // true

API Cheat-Sheet

Category Functions
Numeric compare Lt Lte Gt Gte
Numeric sign Positive Negative NonPositive NonNegative
Numeric arithmetic MultipleOf
Length (str/slice) MaxLength MinLength Length
Size (slice/map) MaxSize MinSize Size
String checks Lowercase Uppercase Includes StartsWith EndsWith
Regex Regex(value, pattern)
Formats Email URL UUID GUID CUID CUID2 NanoID ULID ...
Networks IPv4 IPv6 CIDRv4 CIDRv6
Encoding Base64 Base64URL
Phone & Tokens E164 JWT
ISO ISODateTime ISODate ISOTime ISODuration
JSON JSON
Object Property(obj, key, validator)
MIME Mime(value, allowedTypes)

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Base64

func Base64(value any) bool

Base64 validates if string is valid Base64 encoding

func Base64URL

func Base64URL(value any) bool

Base64URL validates if string is valid Base64URL encoding

func CIDRv4

func CIDRv4(value any) bool

CIDRv4 validates if string is a valid IPv4 CIDR format

func CIDRv6

func CIDRv6(value any) bool

CIDRv6 validates if string is a valid IPv6 CIDR format

func CUID

func CUID(value any) bool

CUID validates if string is a valid CUID format

func CUID2

func CUID2(value any) bool

CUID2 validates if string is a valid CUID2 format

func E164

func E164(value any) bool

E164 validates if string is a valid E.164 phone number format

func Email

func Email(value any) bool

Email validates if string is a valid email format

func Emoji added in v0.3.0

func Emoji(value any) bool

Emoji validates if string is valid emoji

func EndsWith

func EndsWith(value any, suffix string) bool

EndsWith validates if string ends with the suffix

func GUID

func GUID(value any) bool

GUID validates if string is a valid GUID format

func Gt

func Gt(value, limit any) bool

Gt validates if value is greater than limit

func Gte

func Gte(value, limit any) bool

Gte validates if value is greater than or equal to limit

func IPv4

func IPv4(value any) bool

IPv4 validates if string is a valid IPv4 address

func IPv6

func IPv6(value any) bool

IPv6 validates if string is a valid IPv6 address

func ISODate

func ISODate(value any) bool

ISODate validates if string is a valid ISO date format

func ISODateTime

func ISODateTime(value any) bool

ISODateTime validates if string is a valid ISO datetime format

func ISODateTimeWithOptions added in v0.3.0

func ISODateTimeWithOptions(value any, options ISODateTimeOptions) bool

ISODateTimeWithOptions validates if string is a valid ISO datetime format with options

func ISODuration

func ISODuration(value any) bool

ISODuration validates if string is a valid ISO 8601 duration format

func ISOTime

func ISOTime(value any) bool

ISOTime validates if string is a valid ISO time format

func ISOTimeWithOptions added in v0.3.0

func ISOTimeWithOptions(value any, options ISOTimeOptions) bool

ISOTimeWithOptions validates if string is a valid ISO time format with options

func Includes

func Includes(value any, substring string) bool

Includes validates if string contains the substring

func JSON

func JSON(value any) bool

JSON validates if string is valid JSON

func JWT

func JWT(value any) bool

JWT validates if string is a valid JWT token format This function only validates the JWT structure and basic claims It does NOT verify the signature (use JWTWithSecret for signature verification)

func JWTWithOptions added in v0.3.0

func JWTWithOptions(value any, options JWTOptions) bool

JWTWithOptions validates if string is a valid JWT token format with algorithm constraint This function only validates the JWT structure and basic claims It does NOT verify the signature (use JWTWithSecret for signature verification)

func KSUID

func KSUID(value any) bool

KSUID validates if string is a valid KSUID format

func Length

func Length(value any, expected int) bool

Length validates if value's length equals exactly the expected length

func Lowercase

func Lowercase(value any) bool

Lowercase validates if string is all lowercase

func Lt

func Lt(value, limit any) bool

Lt validates if value is less than limit

func Lte

func Lte(value, limit any) bool

Lte validates if value is less than or equal to limit

func MaxLength

func MaxLength(value any, maximum int) bool

MaxLength validates if value's length is at most maximum

func MaxSize

func MaxSize(value any, maximum int) bool

MaxSize validates if collection's size is at most maximum

func Mime

func Mime(value any, allowedTypes []string) bool

Mime validates if value has allowed MIME types

func MinLength

func MinLength(value any, minimum int) bool

MinLength validates if value's length is at least minimum

func MinSize

func MinSize(value any, minimum int) bool

MinSize validates if collection's size is at least minimum

func MultipleOf

func MultipleOf(value, divisor any) bool

MultipleOf validates if value is a multiple of the given divisor

func NanoID

func NanoID(value any) bool

NanoID validates if string is a valid NanoID format

func Negative

func Negative(value any) bool

Negative validates if numeric value is negative (< 0)

func NonNegative

func NonNegative(value any) bool

NonNegative validates if numeric value is non-negative (>= 0)

func NonPositive

func NonPositive(value any) bool

NonPositive validates if numeric value is non-positive (<= 0)

func Positive

func Positive(value any) bool

Positive validates if numeric value is positive (> 0)

func Property

func Property(obj any, key string, validator func(any) bool) bool

Property validates if object has a property that passes validation

func Regex

func Regex(value any, pattern *regexp.Regexp) bool

Regex validates if string matches the pattern

func Size

func Size(value any, expected int) bool

Size validates if collection's size equals exactly the expected size

func StartsWith

func StartsWith(value any, prefix string) bool

StartsWith validates if string starts with the prefix

func ULID

func ULID(value any) bool

ULID validates if string is a valid ULID format

func URL

func URL(value any) bool

URL validates if string is a valid URL format

func URLWithOptions added in v0.3.0

func URLWithOptions(value any, options URLOptions) bool

URLWithOptions validates if string is a valid URL format with optional constraints

func UUID

func UUID(value any) bool

UUID validates if string is a valid UUID format

func Uppercase

func Uppercase(value any) bool

Uppercase validates if string is all uppercase

func XID

func XID(value any) bool

XID validates if string is a valid XID format

Types

type ISODateTimeOptions added in v0.3.0

type ISODateTimeOptions struct {
	// Precision specifies number of decimal places for seconds
	// If nil, matches any number of decimal places
	// If 0 or negative, no decimal places allowed
	Precision *int

	// Offset if true, allows timezone offsets like +01:00
	Offset bool

	// Local if true, makes the 'Z' timezone marker optional
	Local bool
}

ISODateTimeOptions defines parameters for ISO datetime validation

type ISOTimeOptions added in v0.3.0

type ISOTimeOptions struct {
	// Precision specifies number of decimal places for seconds
	// If nil, matches any number of decimal places
	// If 0 or negative, no decimal places allowed
	// Special case: -1 means minute precision only (no seconds)
	Precision *int
}

ISOTimeOptions defines parameters for ISO time validation

type JWTOptions added in v0.3.0

type JWTOptions struct {
	// Algorithm specifies the expected signing algorithm
	// If nil, any algorithm is accepted (not recommended for production)
	Algorithm *string
}

JWTOptions defines options for JWT validation

type URLOptions added in v0.3.0

type URLOptions struct {
	// Hostname validation pattern
	Hostname *regexp.Regexp
	// Protocol validation pattern
	Protocol *regexp.Regexp
}

URLOptions defines options for URL validation

Jump to

Keyboard shortcuts

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