Documentation
¶
Overview ¶
Package validation validates incoming request data against declarative rules before a handler uses it.
Define a form struct with json tags and a Rules method that binds rules to its fields with For and go.laravel.com/validation/rule.Field:
type StorePost struct {
Title string `json:"title"`
Tags []string `json:"tags"`
}
func (f *StorePost) Rules() validation.Rules {
return validation.For(f,
rule.Field(&f.Title, rule.Required, rule.Max(255)),
rule.Field(&f.Tags, rule.Each(rule.Distinct)),
)
}
Validate and bind the request in a handler in one step:
form, err := r.Validate[StorePost]()
if err != nil {
return web.Fail(err)
}
Built-in rules live in the rule subpackage. Call Validate directly when validating a struct outside an HTTP request, or implement Rule for custom checks.
Index ¶
- type Errors
- type Failure
- type Field
- func (f Field) Bound() (any, bool)
- func (f Field) Confirmation() Field
- func (f Field) Empty() bool
- func (f Field) Fail(message string) error
- func (f Field) File() (File, bool)
- func (f Field) Input() map[string]any
- func (f Field) Items() []Field
- func (f Field) Kind() Kind
- func (f Field) Label() string
- func (f Field) Name() string
- func (f Field) Number() (float64, bool)
- func (f Field) NumberText() string
- func (f Field) Other(path string) Field
- func (f Field) Repeated() bool
- func (f Field) Size() (float64, bool)
- func (f Field) String() string
- func (f Field) Type() reflect.Type
- type FieldError
- type FieldRules
- type File
- type Input
- type Kind
- type Rule
- type RuleResolver
- type Rules
- type Sometimes
- type Validator
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Errors ¶
type Errors []FieldError
Errors lists all fields that failed validation, ordered to match the target struct's field declaration order. It marshals to JSON as an object mapping each field path to its slice of messages in that same order.
func Validate ¶
Validate checks target's fields directly, without an HTTP request, and returns any failing fields as Errors, ordered to match target's struct fields. If a rule returns an error that is not a *Failure, Validate stops and returns that error.
When no fields are passed, Validate runs target's Rules() Rules method if it defines one. When fields are passed, Validate builds rules for target with For and uses them in place of target's own Rules method. Embedded and nested structs inside target that define a Rules method are validated automatically; pointer fields to nested structs are validated only when non-nil.
Validate panics if target is nil or not a pointer to a struct, or if any passed FieldRules does not refer to an exported field of target.
func (*Errors) Add ¶
Add appends message to the errors for path, creating a new FieldError at the end if path has no errors yet:
var invalid validation.Errors
invalid.Add("items.0.quantity", "Only 3 are left in stock.")
func (Errors) MarshalJSONTo ¶
MarshalJSONTo encodes e as a JSON object mapping each field path to its slice of error messages, preserving field order.
type Failure ¶
type Failure struct {
// Rule names the failed rule, such as "max", used to look up the default
// message.
Rule string
// Message is an explicit message template supporting placeholders such as
// :attribute. Leave it empty to use the default message for Rule.
Message string
// Replace supplies values for additional message placeholders, such as
// "max": "255" for :max.
Replace map[string]string
}
type Field ¶
type Field struct {
// Path is the field's dot-separated path in the input, such as "items.2.sku".
Path string
// Value is the field's value: the bound Go value from Input.Target when
// present and valid, a [File] (or []any of [File]) for uploads, the raw
// decoded value for any fields, or nil when omitted or null.
Value any
// Present reports whether the input included the field, even with a null
// value. When validating a struct directly without Input.Data, non-Sometimes
// fields are present and [Sometimes] fields report their Present flag.
Present bool
// contains filtered or unexported fields
}
Field carries the path, value, and context of a single field being checked by a Rule.
func (Field) Bound ¶
Bound returns the typed Go value bound into Input.Target for this field when Input.Target is set, the field is present and non-null, did not fail binding, and has a concrete (non-interface) Go type. Pointers and Sometimes wrappers are unwrapped.
func (Field) Confirmation ¶
Confirmation returns the sibling confirmation field (<name>_confirmation) checked by go.laravel.com/validation/rule.Confirmed. When the confirmation field is not declared on the target struct, it applies this field's transform tag so transformed fields match confirmations submitted with the original casing.
func (Field) Empty ¶
Empty reports whether the field is missing, null, whitespace-only text, or an empty slice or map. Zero numbers and false booleans are not empty.
func (Field) Fail ¶
Fail returns a *Failure with the given message template for use in custom Rule implementations. The message may contain :attribute for the field's label.
func (Field) File ¶
File returns the uploaded File held by the field and reports whether f.Value is a File.
func (Field) Input ¶
Input returns the full input map, including uploaded files at their dot paths, so a rule can inspect fields outside the current nested struct (such as a top-level currency from inside an OrderItem rule).
func (Field) Items ¶
Items returns the child fields of a list or map field in order. For a fixed-size array field whose input is a list or index map with fewer items than the array's length, Items also includes the unsubmitted slots with Present false and Value nil.
func (Field) Kind ¶
Kind returns the field's Kind, inferred from the target Go struct field type or from f.Value when the target type does not specify one (such as an any field).
func (Field) Label ¶
Label returns the human-readable field name used in error messages: the label set on the field (with its :index and :position filled in), or the field path converted to lowercase words (so "last_name" and "lastName" become "last name").
func (Field) Name ¶
Name returns the field's path relative to the struct whose Rules method is checking it, matching the path format used by Field.Other. For example, a rule on an OrderItem at "items.2.quantity" sees "quantity".
func (Field) Number ¶
Number parses the field's value as a finite float64 from a numeric value or a numeric string such as "42.5". Non-finite floats (NaN, +Inf, -Inf) and strings such as "NaN", "Infinity", "1_000", or "0x1p10" return false.
func (Field) NumberText ¶
NumberText returns the original spelling of a submitted number when available, or Field.String otherwise.
func (Field) Other ¶
Other looks up a sibling field relative to the struct whose Rules method is currently running, such as a field used for comparison. Inside an OrderItem's own Rules method at "items.2.price", Other("cost") resolves to "items.2.cost".
func (Field) Repeated ¶
Repeated reports whether another field matched by the same wildcard rule holds the same value, such as another entry of a slice validated with rule.Each(rule.Distinct). Inside a nested struct's Rules method, comparisons stay within that struct instance (so a track's artists compare only against that track's artists). Concrete Go types compare by their canonical bound values, while untyped any values compare structurally.
func (Field) Size ¶
Size returns the field's size according to its Kind: Unicode characters for Text, numeric value for Number, element count for List, or kilobytes for Upload. It returns false when f.Value does not match its kind, such as non-numeric text in a number field.
func (Field) String ¶
String returns the field's value as text: strings verbatim, numbers and booleans formatted as text, encoding.TextMarshaler values via MarshalText, and an empty string for all other types.
type FieldError ¶
FieldError holds the validation error messages for a single failed field.
type FieldRules ¶
type FieldRules interface {
// FieldSpec returns the field pointer, rules, optional display label, and
// optional type-mismatch message for one field.
FieldSpec() (ptr any, rules []Rule, label, invalid string)
}
FieldRules describes the validation rules, display label, and type-mismatch message for a single field, built with go.laravel.com/validation/rule.Field.
type File ¶
type File interface {
// Name returns the original filename sent by the client.
Name() string
// Size returns the file size in bytes.
Size() int64
// ContentType returns the MIME type detected from the file contents.
ContentType() string
// Extension returns the file extension inferred from the file contents,
// without a leading dot.
Extension() string
// Open opens the uploaded file for reading.
Open() (io.ReadCloser, error)
}
File represents an uploaded file inspected by file validation rules.
type Input ¶
type Input struct {
// Target is a required non-nil pointer to the bound struct being validated.
// When Data and Files are empty, Validate inspects Target's Go fields
// directly. Nested structs' Rules methods run on each bound instance so
// rules may inspect bound values with rule.When.
Target any
// Data optionally holds the merged request parameters (such as query or
// body input) that were bound into Target. When nil (and Files is empty),
// presence and values are read directly from Target.
Data map[string]any
// Files holds uploaded files keyed by JSON Pointer (RFC 6901), such as
// "/attachment" or "/items/0/file".
Files map[jsontext.Pointer][]File
// Invalid holds fields whose raw values could not bind to Target (such as
// non-numeric text for an int field), keyed by JSON Pointer and mapped to
// the [Failure] to report. Rules are skipped for fields present in Invalid.
Invalid map[jsontext.Pointer]Failure
// NumberText holds original JSON number tokens keyed by JSON Pointer when
// numeric values lose their spelling or precision during decoding.
NumberText map[jsontext.Pointer]string
// DefaultsFromTarget, when true alongside Data, evaluates non-implicit
// rules on omitted fields and cross-field Field.Other lookups against
// non-zero values already held on Target (as web.Request.QueryInto does)
// while implicit presence rules such as Required still check Data.
DefaultsFromTarget bool
// RuleResolver optionally invokes caller-specific Rules signatures on the
// root form, embedded structs, and nested structs.
RuleResolver RuleResolver
// Fields optionally supplies inline field rules built with
// [go.laravel.com/validation/rule.Field] for Target, replacing Target's own
// Rules method when non-empty.
Fields []FieldRules
}
Input holds the bound target struct pointer and optional request data, uploaded files, binding mismatches, and numeric tokens checked by a Validator.
func (Input) Mismatches ¶
Mismatches returns Errors for every entry in in.Invalid, ordered to match the struct fields in in.Target, without running any validation rules.
type Kind ¶
type Kind int
Kind classifies a field's value so size rules measure it appropriately: character count for Text, numeric value for Number, element count for List, and kilobytes for Upload.
const ( // Unknown represents a field whose type and value have no size measure, such // as a bool. Unknown Kind = iota // Text represents a string field measured in Unicode characters. Text // Number represents an integer, float, or [numeric.Decimal] field measured // by its numeric value. Number // List represents a slice, array, or map field measured by its item count. List // Upload represents an uploaded [File] measured in kilobytes. Upload )
type Rule ¶
Rule validates a single Field. Validate returns nil when the field passes, a *Failure when it fails validation, or any other error when validation cannot complete (such as a failed database query). Non-Failure errors abort validation and propagate to the caller.
Rules are skipped for missing, null, or blank fields unless the rule also implements an Implicit() bool method that returns true. When an implicit rule fails, no further rules run on that field.
type RuleResolver ¶
type RuleResolver interface {
// SupportsRules reports whether ResolveRules can invoke the Rules method on
// pointer type t.
SupportsRules(t reflect.Type) bool
// ResolveRules invokes target's Rules method and returns its rules or any
// error it produces.
ResolveRules(target any) (Rules, error)
}
RuleResolver resolves validation rules for structs that declare a Rules method with a caller-specific signature beyond Rules() Rules, such as web's Rules(*web.Request) (Rules, error).
type Rules ¶
type Rules struct {
// contains filtered or unexported fields
}
Rules holds the validation rules, field labels, and type-mismatch messages for a struct. Build Rules with For and go.laravel.com/validation/rule.Field.
func For ¶
func For[S any](target *S, fields ...FieldRules) Rules
For builds a Rules set for target, a non-nil pointer to a struct, resolving each FieldRules pointer against target's fields using their json tags (or Go field names when untagged):
func (f *StorePost) Rules() validation.Rules {
return validation.For(f,
rule.Field(&f.Title, rule.Required, rule.Max(255)),
rule.Field(&f.Body, rule.Required),
)
}
For panics if target is nil or not a pointer to a struct, if any field pointer does not refer to an exported field of target (or reaches through a pointer field), or if [rule.Each] is applied to a non-collection field. For also panics if a referenced field's path uses a JSON name containing a dot or the literal name "*". Use JSON names without validation path syntax.
type Sometimes ¶
Sometimes wraps a field that a request may omit entirely, such as a JSON PATCH payload sending only changed fields. Present reports whether the request included the field (even as null), and Value holds the decoded value:
type EditProfile struct {
Name validation.Sometimes[string] `json:"name"`
Bio validation.Sometimes[*string] `json:"bio"`
}
Request binding and validation populate Sometimes automatically. When the request omits the field, validation skips every rule on the field (including required rules) as well as any rules on nested fields inside it.
Sometimes marshals as its Value. Tagging the field with omitzero omits it from JSON output whenever Present is false.
func (Sometimes[T]) MarshalJSONTo ¶
MarshalJSONTo encodes s.Value as JSON.
func (Sometimes[T]) OptionalValue ¶
OptionalValue returns s.Value and whether the request included the field. Database and model writes read this method to unwrap present values and skip omitted fields when a Sometimes value is passed in db.Values.
type Validator ¶
type Validator struct {
Rules Rules
}
Validator checks an Input against a set of rules.
When Rules is empty and Input.Target implements Rules() Rules, Validator calls that method automatically.
func (Validator) Validate ¶
Validate checks in against v's rules and returns any failing fields as Errors, ordered to match the struct fields in in.Target. If a rule returns an error that is not a *Failure, Validate stops and returns that error.
Validate panics if in.Target is nil or not a pointer to a struct.
Nested structs inside in.Target that define their own Rules method (such as an Address field or an OrderItem slice element) are validated automatically. Pointer fields to nested structs are validated only when non-nil.