validate

package module
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Sep 3, 2026 License: MIT Imports: 13 Imported by: 0

README

common/validate

Struct-tag-driven data validation with built-in rules, custom rule registration, nested struct validation, and slice validation.

Quick Start

import "github.com/LingByte/ling-base/common/validate"

type User struct {
    Name     string `validate:"required,min=3,max=50"`
    Email    string `validate:"required,email"`
    Age      int    `validate:"min=18,max=120"`
    Password string `validate:"required,min=8"`
    Confirm  string `validate:"eqfield=Password"`
}

user := User{Name: "ab", Email: "invalid-email", Age: 5}
err := validate.Validate(user)
// err is *validate.Errors with field-specific messages

if errs, ok := err.(validate.Errors); ok {
    for _, fe := range errs {
        fmt.Printf("%s: %s\n", fe.Field, fe.Message)
    }
}

Built-in Rules

Rule Description Example
required Must not be zero value validate:"required"
min=N Min value (numbers) or length (strings/slices) validate:"min=3"
max=N Max value or length validate:"max=50"
len=N Exact length or value validate:"len=10"
eq=N Must equal N validate:"eq=42"
ne=N Must not equal N validate:"ne=0"
gt=N Greater than N validate:"gt=0"
gte=N Greater than or equal validate:"gte=18"
lt=N Less than N validate:"lt=100"
lte=N Less than or equal validate:"lte=120"
oneof=a b c Must be one of listed values validate:"oneof=red green blue"
email Valid email address validate:"email"
url Valid URL validate:"url"
ip Valid IP address validate:"ip"
ipv4 Valid IPv4 validate:"ipv4"
ipv6 Valid IPv6 validate:"ipv6"
alpha Only alpha characters validate:"alpha"
alphanum Only alphanumeric validate:"alphanum"
numeric Only numeric characters validate:"numeric"
contains=s Must contain substring validate:"contains=@
startswith=s Must start with s validate:"startswith=usr_"
endswith=s Must end with s validate:"endswith=.com"
regex=pattern Must match regex validate:"regex=^[A-Z]{2}$"
eqfield=Name Must equal another field validate:"eqfield=Password"
nefield=Name Must not equal another field validate:"nefield=Username"
gtfield=Name Must be greater than field validate:"gtfield=MinPrice"
gtefield=Name Must be >= field validate:"gtefield=StartDate"
ltefield=Name Must be <= field validate:"ltefield=EndDate"
unique Slice elements must be unique validate:"unique"
dive Validate slice/map elements validate:"dive"
nostructlevel Skip nested struct validation validate:"nostructlevel"

Custom Rules

import (
    "fmt"
    "regexp"
    "github.com/LingByte/ling-base/common/validate"
)

var phoneRegex = regexp.MustCompile(`^\d{11}$`)

validate.AddRule("phone", func(value any, param string, parent any) error {
    s, ok := value.(string)
    if !ok {
        return validate.ErrInvalidType
    }
    if !phoneRegex.MatchString(s) {
        return fmt.Errorf("invalid phone number")
    }
    return nil
})

type Contact struct {
    Phone string `validate:"required,phone"`
}

Nested Validation

Nested structs are validated automatically:

type Address struct {
    Street string `validate:"required"`
    City   string `validate:"required"`
}

type User struct {
    Name    string  `validate:"required"`
    Address Address `validate:"required"`
}

// If Address fields are empty, errors will include "Address.Street" etc.

Slice Validation with dive

type Team struct {
    Members []Member `validate:"required,dive"`
}

type Member struct {
    Name  string `validate:"required,min=2"`
    Email string `validate:"required,email"`
}

// Each element in Members is validated individually.
// Errors include "Members[0].Email", "Members[1].Name", etc.

Single Value Validation

err := validate.ValidateWithTag("test@example.com", "required,email")
// nil if valid

Error Handling

err := validate.Validate(user)
if err != nil {
    errs := err.(validate.Errors)
    if errs.Has("Email") {
        // handle email error
    }
    for _, fe := range errs {
        fmt.Printf("%s: %s (rule: %s)\n", fe.Field, fe.Message, fe.Rule)
    }
}

Slice / Map Validation (standalone)

Validate slices and maps outside of a struct context:

// Validate each element of a slice
errs := validate.ValidateSlice([]string{"a", "ab", "abc"}, "min=2")
// errs[0] = error for "a" (length < 2)
// errs is nil if all valid

// Validate each value in a map
errs := validate.ValidateMap(map[string]int{"a": 1, "b": 5}, "gt=3")
// errs["a"] = error for 1 (not > 3)

Rule Introspection

// Check if a rule exists
validate.HasRule("email")    // true
validate.HasRule("phone")    // false (unless custom-added)

// List all registered rules
rules := validate.RegisteredRules()

// Reset to default rules (removes custom rules)
validate.ResetRules()

License

MIT

Documentation

Overview

Package validate provides struct-tag-driven data validation with built-in rules, custom rule registration, nested struct validation, and slice validation.

Quick Start

type User struct {
    Name     string `validate:"required,min=3,max=50"`
    Email    string `validate:"required,email"`
    Age      int    `validate:"min=18,max=120"`
    Password string `validate:"required,min=8"`
    Confirm  string `validate:"eqfield=Password"`
}

user := User{Name: "ab", Email: "invalid", Age: 5}
err := validate.Validate(user)
// → returns *validate.Errors with field-specific messages

Built-in Rules

required          — field must not be zero value
min=N             — minimum value (numbers) or length (strings/slices)
max=N             — maximum value (numbers) or length (strings/slices)
len=N             — exact length (strings/slices) or value (numbers)
eq=N              — must equal N
ne=N              — must not equal N
gt=N              — greater than N
gte=N             — greater than or equal to N
lt=N              — less than N
lte=N             — less than or equal to N
oneof=a b c       — must be one of the listed values
email             — must be a valid email address
url               — must be a valid URL
ip                — must be a valid IP address
ipv4              — must be a valid IPv4 address
ipv6              — must be a valid IPv6 address
alpha             — must contain only alpha characters
alphanum          — must contain only alphanumeric characters
numeric           — must contain only numeric characters
contains=s        — must contain substring s
startswith=s      — must start with s
endswith=s        — must end with s
regex=pattern     — must match the regex pattern
eqfield=Name      — must equal another field's value
nefield=Name      — must not equal another field's value
gtfield=Name      — must be greater than another field's value
ltefield=Name     — must be less than or equal to another field's value
unique            — slice elements must be unique
dive              — validate slice/map elements recursively
nostructlevel     — skip nested struct validation (opt-in)

Custom Rules

validate.AddRule("phone", func(value any, param string, parent any) error {
    s, ok := value.(string)
    if !ok { return validate.ErrInvalidType }
    if !phoneRegex.MatchString(s) {
        return fmt.Errorf("invalid phone number")
    }
    return nil
})

type Contact struct {
    Phone string `validate:"required,phone"`
}

Nested Validation

Nested structs are validated automatically. Use the `dive` rule to validate elements of a slice or values of a map.

type Order struct {
    Items []Item `validate:"required,dive"`
}

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrInvalidType is returned by a rule when the field value is not
	// of the expected type.
	ErrInvalidType = errors.New("validate: invalid field type for rule")

	// ErrNoValidator is returned when a custom rule is not found.
	ErrNoValidator = errors.New("validate: no validator registered for rule")
)

Sentinel errors.

Functions

func AddRule

func AddRule(name string, fn RuleFunc)

AddRule registers a custom validation rule. The rule name must be lowercase and not conflict with built-in rules (it will overwrite built-in rules if it does).

func HasRule

func HasRule(name string) bool

HasRule returns true if a rule with the given name is registered.

func RegisteredRules

func RegisteredRules() []string

RegisteredRules returns the names of all registered rules (built-in + custom).

func ResetRules

func ResetRules()

ResetRules restores the default built-in rule set, removing any custom rules added via AddRule. This is primarily useful for testing.

func Validate

func Validate(v any) error

Validate validates a struct and returns all field errors. Returns nil if the value is valid. Non-struct values are validated against any rules found in the default tag (not typical — use ValidateWithTag for inline validation).

func ValidateEmail added in v0.1.1

func ValidateEmail(s string) bool

ValidateEmail reports whether s is a valid email address. It uses the same logic as the "email" validation rule (net/mail.ParseAddress).

func ValidateMap

func ValidateMap(m any, tag string) map[any]error

ValidateMap validates each value in a map against the given tag. Returns a map of key → error for all invalid values. Returns nil if all values are valid.

func ValidateSlice

func ValidateSlice(slice any, tag string) map[int]error

ValidateSlice validates each element of a slice against the given tag. Returns a map of index → error for all invalid elements. Returns nil if all elements are valid.

This is a convenience function for validating slices outside of a struct context:

errs := validate.ValidateSlice([]string{"a", "ab", "abc"}, "min=2")
// errs[0] = error for "a" (length < 2)

func ValidateWithTag

func ValidateWithTag(value any, tag string) error

ValidateWithTag validates a single value against a tag string (e.g. "required,min=3"). This is useful for validating individual values outside of a struct context.

Types

type Errors

type Errors []FieldError

Errors is a collection of field errors.

func (Errors) Error

func (e Errors) Error() string

func (Errors) Fields

func (e Errors) Fields() []string

Fields returns the set of field paths that have errors.

func (Errors) ForField

func (e Errors) ForField(field string) Errors

ForField returns all errors for the given field path.

func (Errors) Has

func (e Errors) Has(field string) bool

Has returns true if any error matches the given field path.

type FieldError

type FieldError struct {
	Field   string // dotted path, e.g. "User.Address.Street"
	Rule    string // rule that failed, e.g. "required", "min"
	Value   any    // the invalid value
	Message string // human-readable error message
}

FieldError describes a validation failure for a single field.

func (FieldError) Error

func (e FieldError) Error() string

type RuleFunc

type RuleFunc func(value any, param string, parent any) error

RuleFunc is a validation rule function.

  • value: the field value to validate
  • param: the rule parameter (e.g. "3" for min=3), empty if none
  • parent: the parent struct (for cross-field rules like eqfield)

Return nil if valid, an error otherwise.

func GetRule

func GetRule(name string) RuleFunc

GetRule returns the rule function for the given name, or nil if not found.

Jump to

Keyboard shortcuts

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