govalidator

package module
v0.3.4 Latest Latest
Warning

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

Go to latest
Published: Sep 13, 2026 License: Apache-2.0 Imports: 17 Imported by: 2 modules, 3 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

govalidator (Flexible validator for GoLang)

Conditional required rules treat nil and empty collections as absent, including collection-valued siblings used by required_with and required_without. Existing scalar and custom IsZero semantics are retained. This does not change ordinary omitempty behavior.

GoReportCard GoDoc

This library is compatible with Go 1.17+

Please refer to CHANGELOG.md if you encounter breaking changes.

Motivation

The goal of this library is to provide flexible go validator for both regular struct and struct with presence set. Presence set if a special part of go struct holding flags about what struct field has been set. For example to use go struct for patch operation, user may only set subset of the whole struct, thus validator has to have ability to discriminate fields that need to be validated dynamically.

Other great project for validating go struct.

Usage

validator := govalidator.New()
validation, err := validator.Validate(someStruct)
The following check have been implemented
  • required
  • alpha
  • alphanum
  • alphaunicode
  • alphaunicodenumeric
  • numeric
  • number
  • hexadecimal
  • hexcolor
  • rgb
  • rgba
  • hsl
  • hsla
  • e164
  • localphone
  • phone
  • email
  • base64
  • base64url
  • isbn10
  • isbn13
  • uuid3
  • uuid4
  • uuid5
  • uuid
  • uuid3rfc4122
  • uuid4rfc4122
  • uuid5rfc4122
  • uuidrfc4122
  • ulid
  • md4
  • md5
  • sha256
  • sha384
  • sha512
  • ripemd128
  • ripemd160
  • tiger128
  • tiger160
  • tiger192
  • ascii
  • printableascii
  • multibyte
  • datauri
  • latitude
  • longitude
  • ssn
  • hostnamerfc952
  • hostnamerfc1123
  • fqdnrfc1123
  • btcaddress
  • urlencoded
  • htmlencoded
  • html
  • jwt
  • bic
  • dnsregexrfc1035label
  • iabCategory
  • iabCategories
  • domain
  • wwwdomain
  • nonwwwDomain
  • gt(N)
  • ge(N)
  • gte(N)
  • lt(N)
  • le(N)
  • lte(N)
  • min(N)
  • max(N)
  • between(min,max)
  • choice(coma separated list of allowed int or string values)
  • oneof(coma separated list of allowed int or string values)
  • contains(text)
  • notcontains(text)
  • startswith(prefix)
  • endswith(suffix)
  • eqfield(OtherField)
  • nefield(OtherField)
  • gtfield(OtherField)
  • required_if(OtherField,value)
  • required_unless(OtherField,value)
  • required_with(OtherField)
  • required_without(OtherField)
  • past
  • future
  • url
  • uri
  • http_url
  • ip
  • ipv4
  • ipv6
  • cidr
  • hostname
  • mac
  • port
  • uuidv7
  • slug
  • semver
  • json
Validation matrix (tag -> Go kinds -> example)
Tag Supported Go kinds Example
required string, bool, int*, uint*, float*, slice, ptr, time.Time Name string `validate:"required"`
gt/ge/gte/lt/le/lte numbers (int*,uint*,float*), string (length), primitive slice elements ([]int,[]string) Age int `validate:"gte(18),lte(65)"`
min/max/between numbers, string (length), slice length, primitive slice elements Code string `validate:"between(3,10)"`
choice/oneof string, int*, pointers to them, primitive slice elements State string `validate:"oneof(AZ,AK,CA)"`
contains/notcontains/startswith/endswith string, *string, []string elements Email string `validate:"contains(@),endswith(.com)"`
eqfield/nefield/gtfield compares current field to another field in same struct Confirm string `validate:"eqfield(Password)"`
required_if/required_unless any field type using emptiness check, based on another field value Phone string `validate:"required_if(Type,mobile)"`
required_with/required_without any field type using emptiness check, based on presence/absence of other fields Phone string `validate:"required_without(Email)"`
past/future time.Time, *time.Time, string, *string (RFC3339/RFC3339Nano/2006-01-02) StartAt string `validate:"future"`
url/uri/http_url string, *string, []string elements Link string `validate:"http_url"`
ip/ipv4/ipv6/cidr string, *string, []string elements Network string `validate:"cidr"`
hostname/mac string, *string, []string elements Host string `validate:"hostname"`
port string, *string, int*, uint*, []string elements Port int `validate:"port"`
uuidv7 string, *string, []string elements ID string `validate:"uuidv7"`
slug string, *string, []string elements Slug string `validate:"slug"`
semver string, *string, []string elements Version string `validate:"semver"`
json string, *string, []string elements, []byte Payload string `validate:"json"`
Regex family (email, alpha, domain, uuid4, etc.) string, *string Email string `validate:"email"`
Additional tag
  • omitempty
  • skipPath - remove path from location
  • presence - presence field
Message template placeholders
  • $field - current field name
  • $value - current field value
  • $param - check parameters joined with comma
  • $otherField - related field for cross/conditional checks

Validation option

  • WithShallow - shallow check
  • WithSetMarker - check only fields marked as present

Contributing to govalidator

govalidator is an open source project and contributors are welcome!

See TODO list

Credits and Acknowledgements

Library Author: Adrian Witas

Field selection, promoted fields and shallow validation

WithFieldFilter(func(string) bool) selects checks for one Validate call. A non-nil filter takes precedence over WithSetMarker and WithCanUseMarkerProvider; the provider is not called. Passing nil restores ordinary marker/full validation. Services can be reused for full and sparse calls in any order. Markers and embedded holders are never changed or allocated.

coverage := map[string]bool{"Name": true, "Address.Name": true}
result, err := service.Validate(ctx, input,
    govalidator.WithFieldFilter(func(path string) bool { return coverage[path] }))

Paths are Go selectors relative to the input root: Name for a top-level or promoted field, Address.Name for a named nested field, and Children.Name for a field in a struct slice. Slice indexes, WithPath and skipPath do not affect filter paths. Selecting a child does not require selecting its parent. Rejected fields never execute validation predicates; rules are still compiled and invalid rules return errors. Violation/session paths retain their reporting prefix, skipPath behavior and slice indexes.

Promoted fields follow Go's visible selector rules, including shadowing and ambiguity. Anonymous holders are transparent: if a holder is nil, selected promoted leaf checks receive nil as the absent value. This applies in full and shallow validation, including sparse filters. No missing holder or zero-value replacement is allocated. required and notnull reject absent leaves; conditional and custom predicates evaluate absence with the original field metadata, parent session and diagnostic path. omitempty may skip absent checks. Absent slices have no elements to check, but their field rules still run. Rules on the holder itself also run when selected.

Shallow validation checks visible/promoted fields and primitive-slice rules, including rules declared on named object containers, but does not recurse into named struct fields or struct-slice children.

Direct []string and []int fields retain element execution for ordinary built-in and registered custom checks. required, notnull and conditional required rules run on the field itself. For example, []int with validate:"required,gt(0)" must be nonempty and contain positive integers; element violations use paths such as Scores[0].

Other slices, including []byte, []bool, other numeric slices, and pointers to slices, retain whole-field execution in both full and shallow validation. Their predicates receive the complete declared value (including nil/empty slices or slice pointers), with the containing struct as Session.ParentValue. For example, json checks the complete []byte payload, and min(1) on []bool checks its length. A predicate's type support and meaning remain defined by its factory; validation does not reinterpret these shapes as element checks.

Aliases inherit their resolved rule scope. An alias combining field and element checks on a direct string/int slice is rejected. All predicates for a declared field receive the same canonical *Field at construction and through Session.Field, with its complete original Tag.Checks metadata. Private plan indexes separate execution groups. Field and FieldCheck retain their original three-field public layouts, including positional source literals. omitempty retains its native emptiness semantics.

Null validation

validate:"notnull" checks Go nil and SQL NULL. Zero numbers, false, empty strings and nonnil empty slices/maps pass. Nil pointers, slices, maps and interfaces fail. Values implementing database/sql/driver.Valuer, including sql.Null*, are converted using the standard driver's parameter converter: SQL NULL fails, and conversion errors (including invalid driver values) propagate from Validate. A typed nil byte slice returned by a valuer also fails.

required remains a nonzero/nonempty check for scalars/slices, a nonnil check for pointers, and an IsZero check for supported structs. It is not a SQL null rule.

Nil interfaces, typed nil struct pointers, nil pointer chains to structs/slices, and nil struct-slice elements have no fields to validate and succeed. Unsupported root kinds return errors. Unknown rules and missing, empty or cyclic aliases return explicit compilation errors; a custom factory returning a nil predicate also returns an error.

Temporary rule availability

WithDeferredFields(func(string) bool) marks temporarily unavailable input fields independently of WithFieldFilter. A selected available field can run an independent rule while a sibling-dependent rule waits:

type Input struct {
    Name string `validate:"required,eqfield(ID)"`
    ID   string `validate:"required"`
}

deferred := func(name string) bool { return name == "ID" }
result, err := service.Validate(ctx, input,
    govalidator.WithShallow(true),
    govalidator.WithDeferredFields(deferred))

Here Name's required rule runs; its eqfield(ID) rule and ID's own rule wait. A final call with nil deferral runs complete rules under the normal field filter. This API does not perform a final producer pass automatically.

Deferral is initially shallow-only. Every nonnil deferral callback requires WithShallow(true). Marker options require an explicit nonnil field filter, which overrides marker coverage and provider callbacks. Deferred names use the same canonical Go selectors as field filtering; reporting prefixes, skipPath and slice indexes do not change them. Dependencies are visible sibling names, including promoted names, relative to the enclosing shallow struct. Nested or indexed dependency selectors, inaccessible/ambiguous names and set markers are unsupported. A deferred own field is skipped before field access, emptiness checks or conversion. Existing slice field/element scopes and session contexts are preserved.

Built-ins declare self dependencies; comparisons and conditional-required rules also declare their actual sibling parameters. Aliases conservatively combine all member dependencies and wait as a unit when any input is unavailable. Their ordinary first-success predicate semantics remain unchanged when they execute.

Custom registrations can opt into native dependency compilation:

govalidator.RegisterWithDependencies("custom", newCustomCheck,
    func(field *govalidator.Field, check *govalidator.Check) ([]string, error) {
        return []string{"ID"}, nil
    })

DependencyResolver has signature func(*Field, *Check) ([]string, error). Self is always implicit. A nonnil resolver returning an empty list declares self-only; a nil resolver is opaque, just like the existing Register API. Resolvers run during plan compilation, and their results are copied into private metadata. They receive the same field/check descriptors as the predicate factory. Registrations should be configured before constructing/caching validation plans.

Opaque rules retain normal behavior with nil deferral or a callback that matches no actual input field. When an actual field is deferred, an opaque check on a selected available field fails preflight. Explicitly invalid dependency metadata fails any requested nonnil-deferral preflight for a selected available rule. Omitted and own-deferred rules need not declare dependencies. These decisions are independent of input values, including omitempty, empty slices and nil holders; preflight never assumes an unavailable value is zero.

(*Checks).ValidateAvailability(include, deferred func(string) bool) error preflights immutable shallow metadata without reading inputs or running predicates. Call it for every candidate before executing any candidate when preparing a batch with distinct policies. Service.Validate performs the same preflight for its invocation and snapshots selected fields/runnable rules before execution. No late metadata failure can follow an earlier validation predicate in that invocation. Input fields, markers, holders and compiled descriptors are not mutated. Nil deferral preserves ordinary validation behavior.

Prepared shallow validation

Use a native prepared result when preparation and execution occur in separate phases, especially when preparing all candidates before source access:

checks, err := govalidator.NewChecks(reflect.TypeOf(Input{}))
// Handle err before continuing.
inputNames := checks.InputFields() // detached canonical input names
prepared, err := checks.Prepare(
    govalidator.WithShallow(true),
    govalidator.WithFieldFilter(include),
    govalidator.WithDeferredFields(deferred),
)
// Handle err and finish preparing every candidate before execution.
result, err := prepared.Validate(ctx, input)

Checks.InputFields() []string includes unvalidated sibling inputs as well as validated fields, visible promoted names and named containers. Names are unique and returned in native compiled order. Set markers are excluded. Callers can use this list to freeze input policies without implementing another field mapper. Changing the returned slice does not change the compiled plan.

Checks.Prepare(opts ...Option) (*Prepared, error) requires explicit WithShallow(true). Marker options require a nonnil WithFieldFilter override. It retains the exact compiled Checks and canonical descriptors and captures field/rule choices even when deferral is nil. Preparation does not rerun factories or dependency resolvers. Normal nil-deferral behavior for opaque custom checks remains supported. Failed preparation returns no prepared result.

Prepared.Validate(ctx, value) executes that exact plan and its captured choices without consulting the registry, recompiling, preparing again or rereading coverage/deferred/provider callbacks. It accepts the compiled struct type, pointer chains to that type, and homogeneous root slices of the type or its pointers. Wrong types (including wrong typed nils) return errors before root hooks or unsafe field access. Correctly typed nil roots/elements remain safe.

Options are detached from caller storage. Path nodes are snapshotted at preparation and copied for each execution, including the diagnostic prefix. String/int/int64 keys retain their values; other keys are formatted once during preparation so later mutation cannot change the captured path. Cyclic paths are rejected. A predicate can mutate its session path without altering later calls.

Prepared results can be reused concurrently when predicates are concurrency-safe and inputs are not concurrently mutated. Input payload values are read at execution, so preparation does not clone or freeze the payload. Compiled Checks, Field and FieldCheck descriptors remain shared read-only metadata to preserve factory/session identity. Registry changes and later mutation of resolver-returned storage do not replace the plan or choices already captured by preparation.

For multi-candidate execution, retain one Prepared per candidate after all preparations succeed. ValidateAvailability remains an error-only metadata check; use Prepare when the decisions themselves must survive until execution.

Documentation

Index

Constants

View Source
const (
	//PathKindRoot defines root path kind
	PathKindRoot = PathKind(iota)
	//PathKinField defines field path kind
	PathKinField
	//PathKindKey defines key path kind
	PathKindKey
	//PathKindIndex defines index path kind
	PathKindIndex
)

Variables

View Source
var SessionKey string

SessionKey represents a session key

Functions

func Alias

func Alias(check string) []string

Alias returns tag aliases

func NewBetween added in v0.3.4

func NewBetween() func(field *Field, check *Check) (IsValid, error)

func NewCIDR added in v0.3.4

func NewCIDR() func(field *Field, check *Check) (IsValid, error)

func NewChoice added in v0.1.8

func NewChoice() func(field *Field, check *Check) (IsValid, error)

NewChoice creates choice/enum value checks

func NewContains added in v0.3.4

func NewContains() func(field *Field, check *Check) (IsValid, error)

func NewEndsWith added in v0.3.4

func NewEndsWith() func(field *Field, check *Check) (IsValid, error)

func NewEqField added in v0.3.4

func NewEqField() func(field *Field, check *Check) (IsValid, error)

func NewFuture added in v0.3.4

func NewFuture() func(field *Field, check *Check) (IsValid, error)

func NewGt

func NewGt() func(field *Field, check *Check) (IsValid, error)

NewGt creates greater than validation check

func NewGtField added in v0.3.4

func NewGtField() func(field *Field, check *Check) (IsValid, error)

func NewGte

func NewGte() func(field *Field, check *Check) (IsValid, error)

NewGte creates greater or equal than validation check

func NewHTTPURL added in v0.3.4

func NewHTTPURL() func(field *Field, check *Check) (IsValid, error)

func NewHostname added in v0.3.4

func NewHostname() func(field *Field, check *Check) (IsValid, error)

func NewIP added in v0.3.4

func NewIP() func(field *Field, check *Check) (IsValid, error)

func NewIPv4 added in v0.3.4

func NewIPv4() func(field *Field, check *Check) (IsValid, error)

func NewIPv6 added in v0.3.4

func NewIPv6() func(field *Field, check *Check) (IsValid, error)

func NewJSON added in v0.3.4

func NewJSON() func(field *Field, check *Check) (IsValid, error)

func NewLt

func NewLt() func(field *Field, check *Check) (IsValid, error)

NewLt creates less than validation check

func NewLte

func NewLte() func(field *Field, check *Check) (IsValid, error)

NewLte creates less or equal than validation check

func NewMAC added in v0.3.4

func NewMAC() func(field *Field, check *Check) (IsValid, error)

func NewMax added in v0.3.4

func NewMax() func(field *Field, check *Check) (IsValid, error)

func NewMin added in v0.3.4

func NewMin() func(field *Field, check *Check) (IsValid, error)

func NewNeField added in v0.3.4

func NewNeField() func(field *Field, check *Check) (IsValid, error)

func NewNotContains added in v0.3.4

func NewNotContains() func(field *Field, check *Check) (IsValid, error)

func NewNotRegExprCheck

func NewNotRegExprCheck(expr *regexp.Regexp) func(field *Field, check *Check) (IsValid, error)

func NewPast added in v0.3.4

func NewPast() func(field *Field, check *Check) (IsValid, error)

func NewPort added in v0.3.4

func NewPort() func(field *Field, check *Check) (IsValid, error)

func NewRegExprCheck

func NewRegExprCheck(expr *regexp.Regexp) func(field *Field, check *Check) (IsValid, error)

NewRegExprCheck creates a regexpr based validation check

func NewRegExprCheckWithMinLength

func NewRegExprCheckWithMinLength(expr *regexp.Regexp, minLen int) func(field *Field, check *Check) (IsValid, error)

NewRegExprCheckWithMinLength creates a regexpr based validation check with min Length

func NewRepeatedRegExprCheck

func NewRepeatedRegExprCheck(expr *regexp.Regexp, separator string) func(field *Field, check *Check) (IsValid, error)

func NewRequiredIf added in v0.3.4

func NewRequiredIf() func(field *Field, check *Check) (IsValid, error)

func NewRequiredUnless added in v0.3.4

func NewRequiredUnless() func(field *Field, check *Check) (IsValid, error)

func NewRequiredWith added in v0.3.4

func NewRequiredWith() func(field *Field, check *Check) (IsValid, error)

func NewRequiredWithout added in v0.3.4

func NewRequiredWithout() func(field *Field, check *Check) (IsValid, error)

func NewSemver added in v0.3.4

func NewSemver() func(field *Field, check *Check) (IsValid, error)

func NewSlug added in v0.3.4

func NewSlug() func(field *Field, check *Check) (IsValid, error)

func NewStartsWith added in v0.3.4

func NewStartsWith() func(field *Field, check *Check) (IsValid, error)

func NewURI added in v0.3.4

func NewURI() func(field *Field, check *Check) (IsValid, error)

func NewURL added in v0.3.4

func NewURL() func(field *Field, check *Check) (IsValid, error)

func NewUUIDv7 added in v0.3.4

func NewUUIDv7() func(field *Field, check *Check) (IsValid, error)

func Register

func Register(check string, fn NewIsValid)

Register register tag

func RegisterAlias

func RegisterAlias(check string, checks ...string)

RegisterAlias register tag alias

func RegisterWithDependencies added in v0.3.4

func RegisterWithDependencies(name string, factory NewIsValid, dependencies DependencyResolver)

RegisterWithDependencies registers a check with explicit availability metadata. An empty dependency list declares self-only; a nil resolver remains opaque. Dependencies are canonical visible sibling names, with self always implicit.

func SessionContext

func SessionContext(ctx context.Context, session *Session) context.Context

SessionContext creates a context with session

Types

type CanUseMarkerProvider added in v0.3.0

type CanUseMarkerProvider func(v interface{}) bool

type Check

type Check struct {
	Name       string
	Parameters []string
	Message    string
}

Check represents validation check

type Checks

type Checks struct {
	Type         reflect.Type
	Fields       []*FieldCheck
	Slices       []*Field
	Structs      []*Field
	SimpleSlices []*Field
	// contains filtered or unexported fields
}

Checks represents struct checks

func NewChecks

func NewChecks(t reflect.Type) (*Checks, error)

NewChecks compiles immutable checks for Go-visible fields.

func (*Checks) InputFields added in v0.3.4

func (c *Checks) InputFields() []string

InputFields returns detached canonical names of visible shallow inputs, including unvalidated siblings. Set markers are not validation inputs.

func (*Checks) Prepare added in v0.3.4

func (c *Checks) Prepare(opts ...Option) (*Prepared, error)

Prepare captures field/rule selection without reading input values, running predicates or recompiling Checks. Explicit WithShallow(true) is required. Marker options require a nonnil FieldFilter that overrides marker coverage.

func (*Checks) ValidateAvailability added in v0.3.4

func (c *Checks) ValidateAvailability(include, deferred func(string) bool) error

ValidateAvailability preflights shallow rule availability without reading any input values or executing predicates. include selects fields; deferred marks temporarily unavailable inputs independently of that selection. Nil deferral retains ordinary validation. Preflight every candidate before executing a batch when their include/deferred callbacks differ.

type Choice added in v0.1.8

type Choice struct {
	// contains filtered or unexported fields
}

type DependencyResolver added in v0.3.4

type DependencyResolver func(*Field, *Check) ([]string, error)

DependencyResolver declares additional inputs read by a check. Names are visible Go sibling selectors; self is implicit. A non-nil resolver returning an empty list declares self-only. It runs during native plan compilation.

type Field

type Field struct {
	*Tag
	*xunsafe.Field
	FieldCheck *FieldCheck
}

type FieldCheck

type FieldCheck struct {
	*Field
	Owner   reflect.Type
	IsValid []IsValid
}

FieldCheckPos represents field checks

type IsValid

type IsValid func(ctx context.Context, value interface{}) (bool, error)

IsValid represents a validation function

type NewIsValid

type NewIsValid func(field *Field, check *Check) (IsValid, error)

NewIsValid function to create IsValid

func Lookup

func Lookup(check string) NewIsValid

Lookup returns tag NewIsValid

func LookupAll

func LookupAll(check string) NewIsValid

LookupAll returns a factory, or nil for unknown, empty or cyclic aliases.

type Numeric

type Numeric struct {
	// contains filtered or unexported fields
}

type Option

type Option func(c *Options)

func WithCanUseMarkerProvider added in v0.3.0

func WithCanUseMarkerProvider(provider CanUseMarkerProvider) Option

WithCanUseMarkerProvider creates with marker provider option

func WithDeferredFields added in v0.3.4

func WithDeferredFields(deferred func(string) bool) Option

WithDeferredFields marks temporarily unavailable fields by canonical Go name. Non-nil deferral requires shallow validation and explicit field filtering when marker options are present. Nil retains ordinary complete rule execution.

func WithFieldFilter added in v0.3.4

func WithFieldFilter(filter func(string) bool) Option

WithFieldFilter selects checks by Go selector paths relative to the root. Promoted fields use their visible names; slice indexes, WithPath and skipPath do not affect selection. A non-nil filter overrides marker coverage. Selecting a nested field does not require selecting its traversal containers.

func WithPath

func WithPath(path *Path) Option

WithPath creates with path option

func WithPreservePointer added in v0.2.3

func WithPreservePointer(flag bool) Option

WithPreservePointer creates with preserve pointer option

func WithSetMarker added in v0.2.1

func WithSetMarker() Option

WithSetMarker creates with marker option

func WithShallow

func WithShallow(flag bool) Option

WithShallow creates with shallow option

type Options

type Options struct {
	FieldFilter    func(string) bool
	DeferredFields func(string) bool

	UseMarker       bool
	PreservePointer bool

	Shallow              bool
	Path                 *Path
	CanUseMarkerProvider CanUseMarkerProvider
	// contains filtered or unexported fields
}

type Path

type Path struct {
	Kind  PathKind    `json:",omitempty"`
	Path  *Path       `json:",omitempty"`
	Name  string      `json:",omitempty"`
	Index int         `json:",omitempty"`
	Key   interface{} `json:",omitempty"`
}

Path represents an arbitrary data structure path

func NewPath added in v0.3.0

func NewPath() *Path

NewPath creates a new path

func (*Path) Element

func (p *Path) Element(index int) *Path

Element adds slice element node

func (*Path) Entry

func (p *Path) Entry(name string) *Path

Entry adds map entry node

func (*Path) Field

func (p *Path) Field(name string) *Path

Field add fields node

func (*Path) String

func (p *Path) String() string

String stringifies a path

type PathKind

type PathKind int

PathKind defines patch kind

type Prepared added in v0.3.4

type Prepared struct {
	// contains filtered or unexported fields
}

Prepared retains one exact compiled shallow plan and immutable rule choices. It is reusable; predicates and input values remain the caller's concurrency responsibility. Shared compiled Checks and descriptors must remain read-only.

func (*Prepared) Validate added in v0.3.4

func (p *Prepared) Validate(ctx context.Context, value interface{}) (*Validation, error)

Validate executes the exact Checks and decisions captured by Prepare. Values must have the compiled struct type (optionally through pointers or a single root slice). Type mismatches, including wrong typed nils, fail before access.

type RegExprCheck

type RegExprCheck struct {
	// contains filtered or unexported fields
}

func (*RegExprCheck) IsValidString

func (r *RegExprCheck) IsValidString(ctx context.Context, value interface{}) (bool, error)

func (*RegExprCheck) IsValidStringPtr

func (r *RegExprCheck) IsValidStringPtr(ctx context.Context, value interface{}) (bool, error)

type Service

type Service struct {
	// contains filtered or unexported fields
}

Service represents a service

func New

func New() *Service

func (*Service) Validate

func (s *Service) Validate(ctx context.Context, any interface{}, opts ...Option) (*Validation, error)

type Session

type Session struct {
	Path        *Path
	Field       *Field
	ParentValue interface{}
}

Session represents validation session

func (*Session) Set

func (s *Session) Set(path *Path, field *Field, parentValue interface{})

type Tag

type Tag struct {
	Checks    []Check
	Omitempty bool
	Required  bool
	SkipPath  bool
}

Tag represents validation tag

func ParseTag

func ParseTag(tagString string) *Tag

ParseTag parses rule

type Validation

type Validation struct {
	Violations []*Violation
	Failed     bool
}

func (*Validation) AddViolation added in v0.1.3

func (v *Validation) AddViolation(field string, value interface{}, check string, msg string)

func (*Validation) Append

func (v *Validation) Append(path *Path, field string, value interface{}, check string, msg string, params []string)

func (*Validation) Error

func (e *Validation) Error() string

func (*Validation) String

func (e *Validation) String() string

type Violation

type Violation struct {
	Location string
	Field    string
	Value    interface{}
	Message  string
	Check    string
}

type Zeroable

type Zeroable interface {
	IsZero() bool
}

Jump to

Keyboard shortcuts

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