validate

package
v0.11.7 Latest Latest
Warning

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

Go to latest
Published: Jul 3, 2026 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

Overview

Package validate provides validation functions for various data types and formats.

Key features:

  • Numeric validation (Lt, Gt, Lte, Gte, Positive, Negative, MultipleOf)
  • String validation (Regex, Lowercase, Uppercase, Includes, StartsWith, EndsWith)
  • Format validation (Email, URL, UUID, IP, CIDR, Base64, JWT)
  • ISO datetime validation (ISODateTime, ISODate, ISOTime, ISODuration)
  • Length and size validation (MaxLength, MinLength, MaxSize, MinSize)

Usage:

if validate.Email(email) {
    // valid email
}

if validate.UUID(uuid) {
    // valid UUID
}

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Base64

func Base64(value any) bool

Base64 reports whether the string is valid Base64 encoding.

func Base64URL

func Base64URL(value any) bool

Base64URL reports whether the string is valid Base64URL encoding.

func CIDR added in v0.6.0

func CIDR(value any, version int) bool

CIDR reports whether the string is valid CIDR notation.

func CIDRv4

func CIDRv4(value any) bool

CIDRv4 reports whether the string is a valid IPv4 CIDR notation.

func CIDRv6

func CIDRv6(value any) bool

CIDRv6 reports whether the string is a valid IPv6 CIDR notation.

func CUID

func CUID(value any) bool

CUID reports whether the string is a valid CUID format.

func CUID2

func CUID2(value any) bool

CUID2 reports whether the string is a valid CUID2 format.

func E164

func E164(value any) bool

E164 reports whether the string is a valid E.164 phone number format.

func Email

func Email(value any) bool

Email reports whether the string is a valid email format.

func Emoji added in v0.3.0

func Emoji(value any) bool

Emoji reports whether the string is a valid emoji.

func EndsWith

func EndsWith(value any, suffix string) bool

EndsWith reports whether the string ends with the suffix.

func GUID

func GUID(value any) bool

GUID reports whether the string is a valid GUID format.

func Gt

func Gt(value, limit any) bool

Gt reports whether value is greater than limit.

func Gte

func Gte(value, limit any) bool

Gte reports whether value is greater than or equal to limit.

func Hex added in v0.5.4

func Hex(value any) bool

Hex reports whether the string is a valid hexadecimal string.

func Hostname added in v0.5.4

func Hostname(value any) bool

Hostname reports whether the string is a valid DNS hostname.

func IPv4

func IPv4(value any) bool

IPv4 reports whether the string is a valid IPv4 address.

func IPv6

func IPv6(value any) bool

IPv6 reports whether the string is a valid IPv6 address.

func ISODate

func ISODate(value any) bool

ISODate reports whether the string is a valid ISO date format.

func ISODateTime

func ISODateTime(value any) bool

ISODateTime reports whether the string is a valid ISO datetime format.

func ISODateTimeWithOptions added in v0.3.0

func ISODateTimeWithOptions(value any, options ISODateTimeOptions) bool

ISODateTimeWithOptions reports whether the string is a valid ISO datetime with the given options.

func ISODuration

func ISODuration(value any) bool

ISODuration reports whether the string is a valid ISO 8601 duration format.

func ISOTime

func ISOTime(value any) bool

ISOTime reports whether the string is a valid ISO time format.

func ISOTimeWithOptions added in v0.3.0

func ISOTimeWithOptions(value any, options ISOTimeOptions) bool

ISOTimeWithOptions reports whether the string is a valid ISO time with the given options.

func Includes

func Includes(value any, substring string) bool

Includes reports whether the string contains the substring.

func JSON

func JSON(value any) bool

JSON reports whether the string is valid JSON.

func JWT

func JWT(value any) bool

JWT reports whether the string is a valid JWT format.

func JWTWithOptions added in v0.3.0

func JWTWithOptions(value any, options JWTOptions) bool

JWTWithOptions reports whether the string is a valid JWT format with an algorithm constraint.

func KSUID

func KSUID(value any) bool

KSUID reports whether the string is a valid KSUID format.

func Length

func Length(value any, expected int) bool

Length reports whether value's length equals exactly the expected length.

func Lowercase

func Lowercase(value any) bool

Lowercase reports whether the string contains no uppercase letters.

func Lt

func Lt(value, limit any) bool

Lt reports whether value is less than limit.

func Lte

func Lte(value, limit any) bool

Lte reports whether value is less than or equal to limit.

func MAC added in v0.5.3

func MAC(value any) bool

MAC reports whether the string is a valid MAC address using the default delimiter.

func MACWithOptions added in v0.5.3

func MACWithOptions(value any, opts MACOptions) bool

MACWithOptions reports whether the string is a valid MAC address with a custom delimiter.

func MD5Hex added in v0.5.4

func MD5Hex(value any) bool

MD5Hex reports whether the string is a valid MD5 hash in hex format (32 chars).

func MaxLength

func MaxLength(value any, maximum int) bool

MaxLength reports whether value's length is at most maximum.

func MaxSize

func MaxSize(value any, maximum int) bool

MaxSize reports whether the collection's size is at most maximum.

func Mime

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

Mime reports whether the value is one of the allowed MIME types.

func MinLength

func MinLength(value any, minimum int) bool

MinLength reports whether value's length is at least minimum.

func MinSize

func MinSize(value any, minimum int) bool

MinSize reports whether the collection's size is at least minimum.

func MultipleOf

func MultipleOf(value, divisor any) bool

MultipleOf reports whether value is a multiple of the given divisor.

func NanoID

func NanoID(value any) bool

NanoID reports whether the string is a valid NanoID format.

func Negative

func Negative(value any) bool

Negative reports whether the numeric value is negative (< 0).

func NonNegative

func NonNegative(value any) bool

NonNegative reports whether the numeric value is non-negative (>= 0).

func NonPositive

func NonPositive(value any) bool

NonPositive reports whether the numeric value is non-positive (<= 0).

func Positive

func Positive(value any) bool

Positive reports whether the numeric value is positive (> 0).

func Property

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

Property reports whether the object has a property at key that passes the validator.

func Regex

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

Regex reports whether the string matches the pattern.

func SHA1Hex added in v0.5.4

func SHA1Hex(value any) bool

SHA1Hex reports whether the string is a valid SHA-1 hash in hex format (40 chars).

func SHA256Hex added in v0.5.4

func SHA256Hex(value any) bool

SHA256Hex reports whether the string is a valid SHA-256 hash in hex format (64 chars).

func SHA384Hex added in v0.5.4

func SHA384Hex(value any) bool

SHA384Hex reports whether the string is a valid SHA-384 hash in hex format (96 chars).

func SHA512Hex added in v0.5.4

func SHA512Hex(value any) bool

SHA512Hex reports whether the string is a valid SHA-512 hash in hex format (128 chars).

func Size

func Size(value any, expected int) bool

Size reports whether the collection's size equals exactly the expected size.

func StartsWith

func StartsWith(value any, prefix string) bool

StartsWith reports whether the string starts with the prefix.

func ULID

func ULID(value any) bool

ULID reports whether the string is a valid ULID format.

func URL

func URL(value any) bool

URL reports whether the string is a valid URL format.

func URLWithOptions added in v0.3.0

func URLWithOptions(value any, options URLOptions) bool

URLWithOptions reports whether the string is a valid URL with the given constraints.

func UUID

func UUID(value any) bool

UUID reports whether the string is a valid UUID format.

func Uppercase

func Uppercase(value any) bool

Uppercase reports whether the string contains no lowercase letters.

func XID

func XID(value any) bool

XID reports whether the 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 allows timezone offsets like +01:00 when true.
	Offset bool

	// Local makes the 'Z' timezone marker optional when true.
	Local bool
}

ISODateTimeOptions configures 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 configures 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 configures JWT validation.

type MACOptions added in v0.5.3

type MACOptions struct {
	// Delimiter specifies the separator between hex pairs.
	// Common delimiters: ":", "-", ".". Default is ":".
	Delimiter string
}

MACOptions configures MAC address validation.

type URLOptions added in v0.3.0

type URLOptions struct {
	// Hostname is a pattern the URL's hostname must match.
	Hostname *regexp.Regexp
	// Protocol is a pattern the URL's scheme must match.
	Protocol *regexp.Regexp
}

URLOptions configures URL validation with hostname and protocol constraints.

Jump to

Keyboard shortcuts

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