Skip to main content
Version: 1.1.0

Constraints Overview

Constraints are validation rules applied to struct fields via struct tags. Pedantigo provides a comprehensive set of built-in constraints covering everything from basic requirements to complex format validation.

Constraint Syntax

Constraints are specified using the pedantigo struct tag. Multiple constraints can be combined with commas, and some accept parameters:

type User struct {
// Basic constraint
Name string `json:"name" pedantigo:"required"`

// Multiple constraints
Email string `json:"email" pedantigo:"required,email"`

// Constraints with parameters
Age int `json:"age" pedantigo:"required,min=18,max=120"`
Username string `json:"username" pedantigo:"minLength=3,maxLength=20,pattern=^[a-z0-9_]+$"`
}

Constraint Categories

Core Constraints

The fundamental constraints applicable across multiple types:

ConstraintParameterDescriptionExample
requiredNoneField must be present in the inputpedantigo:"required"
minNumericMinimum value (numeric) or length (string)pedantigo:"min=18"
maxNumericMaximum value (numeric) or length (string)pedantigo:"max=100"
gtNumericGreater thanpedantigo:"gt=0"
gteNumericGreater than or equalpedantigo:"gte=1"
ltNumericLess thanpedantigo:"lt=100"
lteNumericLess than or equalpedantigo:"lte=99"
eqValueMust equal exact valuepedantigo:"eq=active"
neValueMust NOT equal valuepedantigo:"ne=banned"
oneofSpace-separated valuesMust be one of specified valuespedantigo:"oneof=red green blue"
oneofciSpace-separated valuesCase-insensitive oneofpedantigo:"oneofci=admin user guest"
lenNumericExact length (strings/arrays)pedantigo:"len=32"

See the Numeric Constraints page for detailed numeric range examples.

String Constraints

Specialized constraints for string validation:

ConstraintParameterDescriptionExample
minLengthNumericMinimum string lengthpedantigo:"minLength=3"
maxLengthNumericMaximum string lengthpedantigo:"maxLength=100"
alphaNoneOnly alphabetic characterspedantigo:"alpha"
alphanumNoneOnly letters and numberspedantigo:"alphanum"
asciiNoneOnly ASCII characterspedantigo:"ascii"
lowercaseNoneMust be lowercasepedantigo:"lowercase"
uppercaseNoneMust be uppercasepedantigo:"uppercase"
containsStringMust contain substringpedantigo:"contains=test"
excludesStringMust not contain substringpedantigo:"excludes=forbidden"
startswithStringMust start with prefixpedantigo:"startswith=https://"
endswithStringMust end with suffixpedantigo:"endswith=.com"
strip_whitespaceNoneNo leading/trailing whitespacepedantigo:"strip_whitespace"
patternRegexMatch regex patternpedantigo:"pattern=^[a-z]+$"
regexpRegexMatch regex pattern (alias)pedantigo:"regexp=^[a-z]+$"

See the String Constraints page for detailed string validation examples.

Numeric Constraints

Additional constraints specific to numeric types:

ConstraintParameterDescriptionExample
positiveNoneMust be greater than zeropedantigo:"positive"
negativeNoneMust be less than zeropedantigo:"negative"
multiple_ofNumericMust be divisible by valuepedantigo:"multiple_of=5"
max_digitsNumericMaximum total digitspedantigo:"max_digits=8"
decimal_placesNumericMaximum decimal placespedantigo:"decimal_places=2"
disallow_inf_nanNoneReject infinity and NaN valuespedantigo:"disallow_inf_nan"

See the Numeric Constraints page for detailed numeric validation examples.

Format Constraints

Constraints for common data formats:

ConstraintDescriptionExample
emailValid email address formatpedantigo:"email"
urlValid URL formatpedantigo:"url"
uriValid URI formatpedantigo:"uri"
uuidValid UUID (any version)pedantigo:"uuid"
ipv4Valid IPv4 addresspedantigo:"ipv4"
ipv6Valid IPv6 addresspedantigo:"ipv6"
ipValid IPv4 or IPv6 addresspedantigo:"ip"
cidrValid CIDR notation (IPv4 or IPv6)pedantigo:"cidr"
cidrv4Valid IPv4 CIDR notationpedantigo:"cidrv4"
cidrv6Valid IPv6 CIDR notationpedantigo:"cidrv6"
macValid MAC addresspedantigo:"mac"
hostnameValid hostnamepedantigo:"hostname"
hostname_rfc1123Valid RFC 1123 hostnamepedantigo:"hostname_rfc1123"
fqdnValid fully qualified domain namepedantigo:"fqdn"
portValid port number (0-65535)pedantigo:"port"
tcp_addrValid TCP addresspedantigo:"tcp_addr"
udp_addrValid UDP addresspedantigo:"udp_addr"
tcp4_addrValid TCP4 addresspedantigo:"tcp4_addr"
jsonValid JSON stringpedantigo:"json"
jwtValid JSON Web Tokenpedantigo:"jwt"
semverValid semantic versionpedantigo:"semver"
cronValid cron expressionpedantigo:"cron"
datetimeMatches Go time layoutpedantigo:"datetime=2006-01-02"
ulidValid ULID formatpedantigo:"ulid"

See the Format Constraints page for detailed format validation examples.

Encoding Constraints

Constraints for encoded data formats:

ConstraintDescriptionExample
base64Valid base64 encodingpedantigo:"base64"
base64urlValid URL-safe base64 encodingpedantigo:"base64url"
base64rawurlValid raw URL-safe base64 encodingpedantigo:"base64rawurl"

Hash Constraints

Constraints for validating hash format strings:

ConstraintDescriptionExample
md5Valid MD5 hash formatpedantigo:"md5"
sha256Valid SHA256 hash formatpedantigo:"sha256"
sha384Valid SHA384 hash formatpedantigo:"sha384"
sha512Valid SHA512 hash formatpedantigo:"sha512"
mongodbValid MongoDB ObjectID formatpedantigo:"mongodb"

Finance Constraints

Constraints for financial and cryptocurrency identifiers:

ConstraintDescriptionExample
credit_cardValid credit card number (Luhn check)pedantigo:"credit_card"
luhn_checksumValid Luhn checksumpedantigo:"luhn_checksum"
btc_addrValid Bitcoin address (P2PKH/P2SH)pedantigo:"btc_addr"
btc_addr_bech32Valid Bitcoin bech32 addresspedantigo:"btc_addr_bech32"
eth_addrValid Ethereum addresspedantigo:"eth_addr"

Identity Constraints

Constraints for identification numbers and codes:

ConstraintDescriptionExample
isbnValid ISBN (10 or 13)pedantigo:"isbn"
isbn10Valid ISBN-10pedantigo:"isbn10"
isbn13Valid ISBN-13pedantigo:"isbn13"
issnValid ISSN formatpedantigo:"issn"
ssnValid US Social Security Numberpedantigo:"ssn"
einValid US Employer Identification Numberpedantigo:"ein"
e164Valid E.164 phone number formatpedantigo:"e164"

Geographic Constraints

Constraints for geographic coordinates:

ConstraintDescriptionExample
latitudeValid latitude (-90 to 90)pedantigo:"latitude"
longitudeValid longitude (-180 to 180)pedantigo:"longitude"

Color Constraints

Constraints for color format validation:

ConstraintDescriptionExample
hexcolorValid hex color (#RGB or #RRGGBB)pedantigo:"hexcolor"
rgbValid RGB colorpedantigo:"rgb"
rgbaValid RGBA colorpedantigo:"rgba"
hslValid HSL colorpedantigo:"hsl"
hslaValid HSLA colorpedantigo:"hsla"

ISO Constraints

Constraints for ISO standard codes and formats:

ConstraintParameterDescriptionExample
iso3166_alpha2NoneISO 3166-1 alpha-2 country codepedantigo:"iso3166_alpha2"
iso3166_alpha2_euNoneISO 3166-1 alpha-2 EU country codepedantigo:"iso3166_alpha2_eu"
iso3166_alpha3NoneISO 3166-1 alpha-3 country codepedantigo:"iso3166_alpha3"
iso3166_alpha3_euNoneISO 3166-1 alpha-3 EU country codepedantigo:"iso3166_alpha3_eu"
iso3166_numericNoneISO 3166-1 numeric country codepedantigo:"iso3166_numeric"
iso3166_2NoneISO 3166-2 subdivision codepedantigo:"iso3166_2"
iso4217NoneISO 4217 currency codepedantigo:"iso4217"
iso4217_numericNoneISO 4217 numeric currency codepedantigo:"iso4217_numeric"
postcodeCountry codePostal code for specific countrypedantigo:"postcode=US"
postcode_iso3166_alpha2Country codePostal code (alias for postcode)pedantigo:"postcode_iso3166_alpha2=GB"
bcp47NoneBCP 47 language tagpedantigo:"bcp47"

Filesystem Constraints

Constraints for file and directory path validation:

ConstraintDescriptionExample
filepathValid file pathpedantigo:"filepath"
dirpathValid directory pathpedantigo:"dirpath"
filePath must point to existing filepedantigo:"file"
dirPath must point to existing directorypedantigo:"dir"

Collection Constraints

Constraints for arrays, slices, and maps:

ConstraintParameterDescriptionExample
minItemsNumericMinimum number of itemspedantigo:"minItems=1"
maxItemsNumericMaximum number of itemspedantigo:"maxItems=100"
uniqueNoneAll items must be uniquepedantigo:"unique"

See the Collection Constraints page for detailed collection validation examples.

Default Values

ConstraintParameterDescriptionExample
defaultValueDefault value if field missingpedantigo:"default=active"

Complete Example

Here's a realistic example combining constraints from multiple categories:

package main

import (
"log"
"github.com/smrutai/pedantigo"
)

type UserProfile struct {
// Core constraints
ID string `json:"id" pedantigo:"required,uuid"`
Email string `json:"email" pedantigo:"required,email"`
Username string `json:"username" pedantigo:"required,minLength=3,maxLength=20,alphanum"`

// String constraints
Bio string `json:"bio,omitempty" pedantigo:"maxLength=500"`
Website string `json:"website,omitempty" pedantigo:"url"`

// Numeric constraints
Age int `json:"age" pedantigo:"min=13,max=120"`
Rating float64 `json:"rating,omitempty" pedantigo:"min=0,max=5,decimal_places=1"`

// Geographic constraints
Latitude float64 `json:"latitude,omitempty" pedantigo:"latitude"`
Longitude float64 `json:"longitude,omitempty" pedantigo:"longitude"`

// ISO constraints
Country string `json:"country,omitempty" pedantigo:"iso3166_alpha2"`
Currency string `json:"currency,omitempty" pedantigo:"iso4217"`

// Collection constraints
Tags []string `json:"tags,omitempty" pedantigo:"maxItems=10,unique"`
Roles []string `json:"roles" pedantigo:"minItems=1,oneof=admin moderator user"`

// Enum constraint
Status string `json:"status" pedantigo:"required,oneof=active inactive suspended"`
}

func main() {
jsonData := []byte(`{
"id": "550e8400-e29b-41d4-a716-446655440000",
"email": "alice@example.com",
"username": "alice123",
"bio": "Software engineer and open source enthusiast",
"website": "https://example.com",
"age": 28,
"rating": 4.5,
"latitude": 40.7128,
"longitude": -74.0060,
"country": "US",
"currency": "USD",
"tags": ["golang", "rust", "web"],
"roles": ["user"],
"status": "active"
}`)

user, err := pedantigo.Unmarshal[UserProfile](jsonData)
if err != nil {
log.Fatalf("Validation failed: %v", err)
}

// user is now a fully validated UserProfile
log.Printf("User: %+v", user)
}

Validation Error Handling

When validation fails, Pedantigo returns detailed errors for each field:

user, err := pedantigo.Unmarshal[UserProfile](invalidData)
if err != nil {
if validationErr, ok := err.(*pedantigo.ValidationError); ok {
for _, fieldErr := range validationErr.Errors {
fmt.Printf("Field: %s, Error: %s\n", fieldErr.Field, fieldErr.Message)
}
}
}

Example validation error output:

Field: email, Error: must be a valid email address
Field: age, Error: must be at least 13
Field: rating, Error: must be at most 5
Field: roles, Error: field is required

Context-Aware Constraints

Some constraints behave differently depending on the field type:

  • min/max: For numeric types, validates value range. For strings, validates length. For arrays, validates item count.
  • gt/gte/lt/lte: Works with numeric types and comparable values.
  • len: For strings, validates character count. For arrays/slices, validates element count.

Performance Considerations

Constraint validation in Pedantigo is highly optimized:

  • Format constraints (email, URL, UUID, etc.) use compiled regex patterns cached at startup
  • ISO code validation uses precompiled lookup tables
  • Numeric constraints perform simple arithmetic comparisons
  • String constraints use efficient string operations

See Schema Generation for caching strategy that provides 240x speedup.

Next Steps

Learn more about specific constraint categories: