Help us shape the future of Go! Take the 2026 Go Developer Survey

validation

package module
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Oct 11, 2026 License: Apache-2.0 Imports: 10 Imported by: 1

README ¶

nexssp/validation

nexssp/validation provides high-performance struct and field validation for the Nexss ecosystem using github.com/go-playground/validator/v10.

🚀 Usage Patterns

1. Direct Kernel Action Integration (AutoValidate)
validatedAction := validation.AutoValidate(
    action.New("goal.create", handleGoal),
).Build()
2. Direct Builder Method (.Validate(...))
act := action.New("order.process", handleOrder).
    Validate(func(ctx context.Context, req OrderReq) error {
        return validation.Struct(ctx, req)
    }).
    Build()
3. Pipeline Plugin Hook (validation.New())
plugin := validation.New()

for _, act := range registry.Actions() {
    act.AddAnyHook(plugin.(action.Executable).Describe().Hooks[0])
}
4. Standalone Validation
if err := validation.Struct(ctx, myStruct); err != nil {
    return validation.FromValidatorError(err)
}

Extension Paattern

package main

import (
	"context"

	"github.com/go-playground/validator/v10"
	"github.com/nexssp/validation"
)

// Register domain-specific rules at application cold-start
func init() {
	validation.RegisterCustom("nip", func(_ context.Context, fl validator.FieldLevel) bool {
		return isPolishNIPValid(fl.Field().String())
	})
}

type InvoiceDTO struct {
	TaxID string `json:"tax_id" validate:"required,nip"`
}

func isPolishNIPValid(nip string) bool {
	// App-level or domain-specific package implementation
	return true
}

Documentation ¶

Index ¶

Constants ¶

This section is empty.

Variables ¶

This section is empty.

Functions ¶

func AutoValidate ¶

func AutoValidate[Req, Res any](b *action.Builder[Req, Res]) *action.Builder[Req, Res]

AutoValidate wires Kernel's .Validate(...) builder contract directly to validation.Struct, mapping validator/v10 errors into clean xerr.ValidationDetails.

func CompileWithTimeout ¶

func CompileWithTimeout(pattern string, timeout time.Duration) *regexp.Regexp

CompileWithTimeout prevents ReDoS attacks on dynamic patterns.

func FromValidatorError ¶

func FromValidatorError(err error) *xerr.AppError

FromValidatorError maps validator/v10 field errors to Nexss structured details with short, human-readable messages.

Each ValidationDetail carries:

  • Field: the JSON name of the failing field
  • Validation: the raw validator tag (e.g. "oneof", "min")
  • Value: a short phrase suitable for a per-field error line, written the way a user would describe the problem

The Validation tag is preserved verbatim so callers that branch on it (metrics, i18n, dashboards) keep working unchanged. Only Value is humanized.

func Hook ¶ added in v0.2.0

func Hook() action.AnyHook

Hook returns a stateless validation hook suitable for action.Library.Hooks. The OnBuild predicate drops the hook from every action whose Req type carries no `validate:` tags and does not implement Validatable — such actions pay zero cost in Do().

Usage:

action.MustNewRegistry(action.Library{
    Name:    "myapp",
    Actions: myActions,
    Hooks:   []action.AnyHook{validation.Hook()},
})

func IsValidEmail ¶

func IsValidEmail(email string) bool

func IsValidUUID ¶

func IsValidUUID(id string) bool

func Map ¶ added in v0.3.0

func Map(ctx context.Context, data, rules map[string]any) error

Map validates a runtime map against per-key rule strings. Keys missing from rules are ignored. A nil or empty rules map is a no-op.

Internally each key is validated with Var so the rules syntax is identical to struct tags. The Field component of each returned ValidationDetail is set to the map key.

func RegisterCustom ¶

func RegisterCustom(tag string, fn validator.FuncCtx)

RegisterCustom registers context-aware validation rules safely at cold-path init. Panics if the tag is invalid or already registered: both are programmer errors.

func RegisterType ¶

func RegisterType(fn validator.CustomTypeFunc, types ...any)

RegisterType registers custom type handlers safely at cold-path init.

func Struct ¶

func Struct(ctx context.Context, value any) error

Struct validates exported fields using `validate:"..."` tags. Automatically trims whitespace, evaluates tags, and calls Validatable.Validate() if implemented.

func TrimStringFields ¶

func TrimStringFields(value any)

TrimStringFields recurses through exported string fields in structs, pointers, and slices, trimming leading and trailing whitespace in-place.

func ValidateAction ¶

func ValidateAction[T any](name string) *action.BuiltAction[T, T]

ValidateAction creates an identity action that validates T using validate tags.

func Var ¶ added in v0.3.0

func Var(ctx context.Context, value any, rule string) error

Because Var validates a scalar (not a struct field), the Field component of each returned ValidationDetail is empty. Callers that know the field name (the schema extension does) should overwrite it.

Types ¶

type Validatable ¶

type Validatable interface {
	Validate() error
}

Validatable allows structs to execute custom semantic validation logic after tag validation passes. Implementations must be safe for concurrent use.

Directories ¶

Path Synopsis
examples

Jump to

Keyboard shortcuts

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