validation

package
v1.3.0 Latest Latest
Warning

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

Go to latest
Published: Jul 16, 2026 License: MIT Imports: 12 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func SetDB

func SetDB(fn func() *lucid.DB)

SetDB sets the database provider for unique/exists rules. Call this in your app bootstrap: validation.SetDB(func() *lucid.DB { return database.DB })

func ValidateRequestJSON

func ValidateRequestJSON(body io.Reader, v any) error

ValidateRequestJSON decodes JSON from body into v. No validation. Prefer BindAndValidateSchema or BindAndValidate instead.

func ValidateStruct

func ValidateStruct(s any) error

ValidateStruct validates a struct that implements SchemaProvider using its Rules() schema. Returns nil if valid, or a ValidationErrors (which also implements error) when validation fails.

Usage:

v := &validators.Todo{Title: strings.TrimSpace(input)}
if err := validation.ValidateStruct(v); err != nil {
    // err is a ValidationErrors — render form with errors
}

Types

type ArrayRule

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

ArrayRule validates slice/array fields.

func Array

func Array() *ArrayRule

Array creates a new ArrayRule.

func (*ArrayRule) Each

func (r *ArrayRule) Each(rule Rule) *ArrayRule

Each validates each element with the given rule (e.g., Array().Each(String().Email())).

func (*ArrayRule) IsRequired

func (r *ArrayRule) IsRequired() bool

IsRequired reports whether this rule requires a non-empty slice.

func (*ArrayRule) Max

func (r *ArrayRule) Max(n int) *ArrayRule

Max sets the maximum number of elements.

func (*ArrayRule) Min

func (r *ArrayRule) Min(n int) *ArrayRule

Min sets the minimum number of elements.

func (*ArrayRule) Required

func (r *ArrayRule) Required() *ArrayRule

func (*ArrayRule) TypeScriptType

func (r *ArrayRule) TypeScriptType() string

TypeScriptType returns the TypeScript type string for this rule.

type Authorizer

type Authorizer interface {
	Authorize(c *reqctx.Context) error
}

Authorizer is implemented by request types that perform authorization.

type BaseFormRequest

type BaseFormRequest[T any] struct{}

BaseFormRequest provides a no-op Authorize implementation. Embed it in your request type to only implement Payload().

func (BaseFormRequest[T]) Authorize

func (BaseFormRequest[T]) Authorize(c *reqctx.Context) error

type BoolRule

type BoolRule struct{}

BoolRule validates boolean fields.

func Bool

func Bool() *BoolRule

func (*BoolRule) IsRequired

func (r *BoolRule) IsRequired() bool

IsRequired always returns false for BoolRule (presence is validated by type, not value).

func (*BoolRule) TypeScriptType

func (r *BoolRule) TypeScriptType() string

TypeScriptType returns the TypeScript type string for this rule.

type DateRule

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

DateRule validates string or time.Time fields as dates.

func Date

func Date() *DateRule

Date creates a new DateRule. Default layout is RFC3339.

func (*DateRule) After

func (r *DateRule) After(t time.Time) *DateRule

After validates the date is after the given time.

func (*DateRule) AfterOrEqual

func (r *DateRule) AfterOrEqual(t time.Time) *DateRule

AfterOrEqual validates the date is after or equal to the given time.

func (*DateRule) Before

func (r *DateRule) Before(t time.Time) *DateRule

Before validates the date is before the given time.

func (*DateRule) BeforeOrEqual

func (r *DateRule) BeforeOrEqual(t time.Time) *DateRule

BeforeOrEqual validates the date is before or equal to the given time.

func (*DateRule) DateOnly

func (r *DateRule) DateOnly() *DateRule

DateOnly expects YYYY-MM-DD format.

func (*DateRule) IsRequired

func (r *DateRule) IsRequired() bool

IsRequired reports whether this rule requires a non-zero date.

func (*DateRule) Layout

func (r *DateRule) Layout(layout string) *DateRule

Layout sets the expected date format (Go time layout string).

func (*DateRule) Required

func (r *DateRule) Required() *DateRule

func (*DateRule) TypeScriptType

func (r *DateRule) TypeScriptType() string

TypeScriptType returns the TypeScript type string for this rule (dates are strings in JSON).

type ExistsOpts

type ExistsOpts struct {
	// Table is the database table to check against.
	Table string

	// Column overrides the column name (defaults to the field name).
	Column string

	// Filter adds extra conditions to the query.
	Filter func(db *lucid.DB, value string, field string) *lucid.DB
}

ExistsOpts configures the exists database rule.

Example:

validation.String().Required().Exists(validation.ExistsOpts{
    Table: "categories",
    Column: "slug",
})

type FileRule

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

FileRule validates *multipart.FileHeader fields.

func File

func File() *FileRule

File creates a new FileRule.

func (*FileRule) Extensions

func (r *FileRule) Extensions(exts ...string) *FileRule

Extensions restricts allowed file extensions (without dot).

func (*FileRule) Image

func (r *FileRule) Image() *FileRule

Image restricts to common image MIME types.

func (*FileRule) IsRequired

func (r *FileRule) IsRequired() bool

IsRequired reports whether this rule requires a file to be present.

func (*FileRule) MaxSize

func (r *FileRule) MaxSize(bytes int64) *FileRule

MaxSize sets the maximum file size in bytes.

func (*FileRule) MaxSizeMB

func (r *FileRule) MaxSizeMB(mb int) *FileRule

MaxSizeMB sets the maximum file size in megabytes.

func (*FileRule) MimeTypes

func (r *FileRule) MimeTypes(types ...string) *FileRule

MimeTypes restricts allowed MIME types.

func (*FileRule) Required

func (r *FileRule) Required() *FileRule

func (*FileRule) TypeScriptType

func (r *FileRule) TypeScriptType() string

TypeScriptType returns the TypeScript type string for this rule.

type FormRequest

type FormRequest[T any] interface {
	// Payload returns a pointer to the payload struct with validator tags.
	Payload() *T
	// Authorize returns an error if the request is not authorized.
	Authorize(c *reqctx.Context) error
}

FormRequest defines a JSON form request with validation + authorization. T is the payload type that carries validator tags (legacy) or is validated via a typed Schema using BindAndValidateSchema.

Example:

type LoginPayload struct {
  Email    string `json:"email" validate:"required,email"`
  Password string `json:"password" validate:"required"`
}

type LoginRequest struct {
  validation.BaseFormRequest[LoginPayload]
}

func (r *LoginRequest) Payload() *LoginPayload { return &LoginPayload{} }

func (r *LoginRequest) Authorize(c *http.Context) error {
  return nil // or return an error to deny
}

// In handler:
// req := &LoginRequest{}
// payload, ve, err := validation.BindAndValidate(c, req)
// if ve != nil { return c.JSON(422, ve.ToMap()) }
// if err != nil { return err } // auth failure or other error
// use payload.Email, payload.Password

type MapRule

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

MapRule validates map[string]any fields.

func Map

func Map() *MapRule

Map creates a new MapRule.

func (*MapRule) IsRequired

func (r *MapRule) IsRequired() bool

IsRequired reports whether this rule requires a non-empty map.

func (*MapRule) Keys

func (r *MapRule) Keys(schema Schema) *MapRule

Keys sets nested validation rules for map values.

func (*MapRule) Required

func (r *MapRule) Required() *MapRule

func (*MapRule) TypeScriptType

func (r *MapRule) TypeScriptType() string

TypeScriptType returns the TypeScript type string for this rule.

type MessageProvider

type MessageProvider interface {
	Messages() map[string]string
}

MessageProvider is implemented by request types that provide custom messages.

type NumberRule

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

NumberRule validates numeric fields (int, uint, float).

func Number

func Number() *NumberRule

Number creates a new NumberRule.

func (*NumberRule) Between

func (r *NumberRule) Between(a, b float64) *NumberRule

func (*NumberRule) IsRequired

func (r *NumberRule) IsRequired() bool

IsRequired reports whether this rule requires a non-zero value.

func (*NumberRule) Max

func (r *NumberRule) Max(n float64) *NumberRule

func (*NumberRule) Min

func (r *NumberRule) Min(n float64) *NumberRule

func (*NumberRule) Positive

func (r *NumberRule) Positive() *NumberRule

func (*NumberRule) Required

func (r *NumberRule) Required() *NumberRule

func (*NumberRule) TypeScriptType

func (r *NumberRule) TypeScriptType() string

TypeScriptType returns the TypeScript type string for this rule.

type Preparer

type Preparer interface {
	Prepare()
}

Preparer is implemented by request types that need pre-validation sanitization.

type Rule

type Rule interface {
	// contains filtered or unexported methods
}

Rule is implemented by all typed rules.

type Schema

type Schema map[string]Rule

Schema defines typed validation rules for a request payload. Keys are field names (preferring json tag names).

type SchemaProvider

type SchemaProvider interface {
	Rules() Schema
}

SchemaProvider is implemented by request types that provide typed rules.

type StringRule

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

StringRule validates string fields with a chainable, VineJS-style API.

func String

func String() *StringRule

String creates a new StringRule.

func (*StringRule) Alpha

func (r *StringRule) Alpha() *StringRule

Alpha validates the field contains only letters.

func (*StringRule) AlphaNum

func (r *StringRule) AlphaNum() *StringRule

AlphaNum validates the field contains only letters and digits.

func (*StringRule) Confirmed

func (r *StringRule) Confirmed() *StringRule

Confirmed validates that a matching {field}_confirmation field exists and has the same value. The confirmation field is looked up in the parent struct.

func (*StringRule) Email

func (r *StringRule) Email() *StringRule

Email validates the field as an email address.

func (*StringRule) Exists

func (r *StringRule) Exists(opts ExistsOpts) *StringRule

Exists validates that the value exists in the database. See ExistsOpts.

func (*StringRule) In

func (r *StringRule) In(values ...string) *StringRule

In validates the field value is one of the allowed values.

func (*StringRule) IsRequired

func (r *StringRule) IsRequired() bool

IsRequired reports whether this rule requires a non-empty value.

func (*StringRule) Max

func (r *StringRule) Max(n int) *StringRule

Max sets the maximum length.

func (*StringRule) Min

func (r *StringRule) Min(n int) *StringRule

Min sets the minimum length.

func (*StringRule) Regex

func (r *StringRule) Regex(pattern string) *StringRule

Regex validates the field matches the given pattern.

func (*StringRule) Required

func (r *StringRule) Required() *StringRule

Required marks the field as required (non-empty).

func (*StringRule) Trim

func (r *StringRule) Trim() *StringRule

Trim trims whitespace before validation.

func (*StringRule) TypeScriptType

func (r *StringRule) TypeScriptType() string

TypeScriptType returns the TypeScript type string for this rule.

func (*StringRule) URL

func (r *StringRule) URL() *StringRule

URL validates the field as an absolute URL.

func (*StringRule) Unique

func (r *StringRule) Unique(opts UniqueOpts) *StringRule

Unique validates uniqueness in the database. See UniqueOpts.

type UIntRule

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

UIntRule validates unsigned integer fields.

func UInt

func UInt() *UIntRule

func (*UIntRule) IsRequired

func (r *UIntRule) IsRequired() bool

IsRequired reports whether this rule requires a non-zero value.

func (*UIntRule) Required

func (r *UIntRule) Required() *UIntRule

func (*UIntRule) TypeScriptType

func (r *UIntRule) TypeScriptType() string

TypeScriptType returns the TypeScript type string for this rule.

type UniqueOpts

type UniqueOpts struct {
	// Table is the database table to check against.
	Table string

	// Column overrides the column name (defaults to the field name).
	Column string

	// Filter adds extra conditions to the query (e.g. exclude current record).
	Filter func(db *lucid.DB, value string, field string) *lucid.DB
}

UniqueOpts configures the unique database rule.

Example (AdonisJS VineJS style):

validation.String().Required().Email().Unique(validation.UniqueOpts{
    Table: "users",
    Filter: func(db *lucid.DB, value, field string) *lucid.DB {
        return db.Where("id != ?", currentUserID)
    },
})

type ValidationErrors

type ValidationErrors map[string][]string

ValidationErrors holds field-level validation errors for API responses.

func BindAndValidate

func BindAndValidate[T any](c *reqctx.Context, fr FormRequest[T]) (*T, ValidationErrors, error)

BindAndValidate binds JSON body into the payload, validates it, and runs Authorize. It returns:

  • payload (*T) on success
  • ve (ValidationErrors) when validation fails (for 422 responses)
  • err for non-validation errors (e.g. JSON decode, authorization).

func BindAndValidateSchema

func BindAndValidateSchema(c *reqctx.Context, req any) (ValidationErrors, error)

BindAndValidateSchema binds JSON body into req, runs Prepare (if present), validates using typed Schema rules, and then calls Authorize (if present).

func FormatValidationError

func FormatValidationError(err error) ValidationErrors

FormatValidationError is kept for backward compatibility.

func (ValidationErrors) Error

func (e ValidationErrors) Error() string

Error implements the error interface.

func (ValidationErrors) ToMap

func (e ValidationErrors) ToMap() map[string][]string

ToMap returns the errors as map[string][]string for JSON responses.

type WhenRule

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

WhenRule applies a sub-rule only when a condition is met, providing conditional validation (similar to VineJS's when/otherwise pattern).

Usage:

schema := validation.Schema{
    "role":       validation.String().Required(),
    "company_id": validation.When("role", "business", validation.String().Required()),
    "bio":        validation.WhenFn(func(data map[string]any) bool {
        return data["role"] == "creator"
    }, validation.String().Min(10)),
}

func When

func When(field string, value any, then Rule) *WhenRule

When returns a conditional rule: apply the given rule only when the specified field equals the expected value.

validation.When("type", "premium", validation.String().Required().Min(10))

func WhenFn

func WhenFn(fn func(map[string]any) bool, then Rule) *WhenRule

WhenFn returns a conditional rule: apply the given rule only when predicate returns true.

validation.WhenFn(func(data map[string]any) bool {
    return data["plan"] == "enterprise"
}, validation.String().Required())

func (*WhenRule) Otherwise

func (w *WhenRule) Otherwise(r Rule) *WhenRule

Otherwise sets an alternative rule when the condition is NOT met.

validation.When("role", "admin", validation.String().Required()).
    Otherwise(validation.String().Max(100))

Jump to

Keyboard shortcuts

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